PAT1 1007 Maximum Subsequence Sum

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/LSC_333/article/details/91368464

Topic Link to
my github

Subject to the effect

A string of numbers, and seeking the maximum substring

Entry

Each group contains a test
length of the first line gives the numeric string K 10000 K\leq10000
second line gives K K number to the numeric string representing the

Export

The value of the leftmost and rightmost value of the maximum output substring in a row and then outputs the maximum substring, if there are a plurality of outputs that a minimum standard lower left

Sample input

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

Sample Output

10 1 4

Resolve

Through the array, each digital sum, and if greater than the largest known, it updates the maximum and the lower right mark, and negative if the lower left updated standard

k = int(input())
num = list(map(int, input().split()))
sum, ts, left, right, tl = -1, 0, 0, k - 1, 0
for i in range(k):
    ts += num[i]
    if ts > sum:
        sum = ts
        left = tl
        right = i
    if ts < 0:
        ts = 0
        tl = i + 1
sum=max(sum, 0)
print('%d %d %d' % (sum, num[left], num[right]))
exit(0)

Guess you like

Origin blog.csdn.net/LSC_333/article/details/91368464