【python】PAT甲级1007 Maximum Subsequence Sum (25/25分)

  1. 题目
    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

  1. 代码(动态规划)
k=int(input())
inp=list(map(int,input().split()))
#包含下标count的连续数组中找最大的数组
def m(lst,start,end,count):
    rightl=-float("inf")
    leftl=-float("inf")
    summ=0
    for i in range(count,start-1,-1):
        summ+=lst[i]
        if summ>=leftl:
            ss=i
            leftl=summ
    summ=0
    for i in range(count+1,end+1):
        summ+=lst[i]
        if summ>rightl:
            rightl=summ
            ee=i
    return ss,ee,leftl+rightl
# 比较下标count左边的最大数组,下标count右边的最大数组,包含下标count的最大数组,比较出和最大的连续数组返回其下标和加和
def f(lst,start,end):
    count=(start+end)//2
    if start==end:#一个元素
        return start,end,lst[count]
    aa,bb,left=f(lst,start,count)
    cc,dd,right=f(lst,count+1,end)
    ss,ee,mid=m(lst,start,end,count)
    if left>=right:
        if left>=mid:
            return aa,bb,left
        else:
            return ss,ee,mid
    else:
        if right>mid:
            return cc,dd,right
        else:
            return ss,ee,mid
#处理K个值全为负数的情况
ok=False
for i in range(k):
    if inp[i]>=0:
        ok=True
        break
if ok:
    out1,out2,out0=f(inp,0,k-1)
    print(out0,inp[out1],inp[out2])
else:
    print(0,inp[0],inp[k-1])

你可能感兴趣的:(PAT,python)