[PYTHON](PAT)1007 MAXIMUM SUBSEQUENCE SUM (25)

版权声明:首发于 www.amoshuang.com https://blog.csdn.net/qq_35499060/article/details/82050900

Given a sequence of K integers { N~1~, N~2~, …, N~K~ }. A continuous subsequence is defined to be { N~i~, N~i+1~, …, N~j~ } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10

-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

题目大意:

给定一串整型数字,要求你找出其中和最大的片段,如果总和为该值的片段不唯一,则求片段的开头结尾的索引最小的片段。

扫描二维码关注公众号,回复: 2973245 查看本文章

分析:

遍历数组,使用sums记录最大值,使用temp记录临时和。如果temp大于sums,则更新sums,更新left和right。如果出现了temp小于0,则将temp设为0,放弃包括当前遍历到的元素在内的所有元素,因为负值对后面的累加是没有贡献的。
坑爹的测试点5的数字列表的首元素为0,所以要求一开始将sums设置为-1.

Python实现

Python

if __name__ == "__main__":

    num = int(input())

    line = input().split(" ")

    number = [int(x) for x in line]

    flag = True

    if len([x for x in number if x >= 0]) == 0:

        flag = False

        print(0, number[0], number[-1])

    sums = -1

    temp, tempLeft, index, right, left = 0, 0, 0, 0, 0

    if flag == True:

        while(index != len(number)):

            temp = temp + number[index]

            index += 1

            if temp < 0:

                temp = 0

                tempLeft = index

            elif temp > sums:

                sums = temp

                left = tempLeft

                right = index - 1

        print(sums, number[left], number[right])

更多技术干活,有趣文章,点这里没错

猜你喜欢

转载自blog.csdn.net/qq_35499060/article/details/82050900