算法 Maximum Subsequence Sum

Given a sequence of K integers { N1​​ , N2, ..., NK}. Acontinuous 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

def f_input():
    #-1 2 7 -11 3 7 -12 3 6 -4 10 -14 -14 0 -14 7 7 7
    # num_n没什么用
    num_n = input()
    num_in_li = input().split()

    li = []
    for num_li_n in num_in_li:
        li.append(int(num_li_n))
    return li

def f(li):
    startNum = endNum = num = -1
    tempNum = 0
    # 这里是测试点4  但不知道测的是个什么
    try:
        if li[0] > 0:
            num = li[0]
        tempStartNum = tempEndNum = li[0]
    except:
        return str(startNum), str(endNum), str(num)

    for li_num in li:
        #
        if tempNum < 0:
            #tempNum < 0,li_num > 0  找到一个最大子序列,开始找下一个
            #tempStartNum < 0 and li_num == 0 序列 -1 -1 -1 0         测试点5
            if li_num > 0 or (tempStartNum < 0 and li_num == 0):
                tempStartNum = li_num
            tempNum = 0

        tempNum += li_num
        tempEndNum = li_num

        if tempNum > num:
            startNum = tempStartNum
            endNum = tempEndNum
            num = tempNum

    # 判断是否为全负序列
    if startNum < 0:
        startNum = tempStartNum
    if endNum < 0:
        endNum = tempEndNum
    if num < 0:
        num = 0

    return str(startNum), str(endNum), str(num)

if __name__ == '__main__':
    m_li = f_input()
    sNum, eNum, mNum = f(m_li)
    print(mNum+" "+sNum+" "+eNum)

参考的大佬C算法改的:Maximum Subsequence Sum--14年浙大计算机考研题

你可能感兴趣的:(算法 Maximum Subsequence Sum)