题目
Given a sequence of K integers { N 1 , N 2 N_{1}, N_{2} N1,N2,…, N k N_{k} Nk} . A continuous subsequence is defined to be { N i , N i + 1 N_{i}, N_{i+1} Ni,Ni+1,…, N j N_{j} Nj } where 1 ≤ i ≤ j ≤ K 1≤i≤j≤K 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
解题思路
用动态规划来解这道题,使用一个列表来存储每一个点上的最大和值,所以动态规划的推导式为:
M a x S u m L i s t [ i ] = M a x ( S e q u e n c e L i s t [ i ] , S e q u e n c e L i s t [ i ] + M a x S u m L i s t [ i − 1 ] ) MaxSumList[i]=Max(SequenceList[i],SequenceList[i]+MaxSumList[i-1]) MaxSumList[i]=Max(SequenceList[i],SequenceList[i]+MaxSumList[i−1])
即可得到最大的和值,并记录最大和值的结束点的值和索引,并通过结束点的索引求开始点的值
测试点分析
2
-1 0
# output: 0 0 0
1
0
# output: 0 0 0
3
-1 -2 -3
# output: 0 -1 -3
代码
num = int(input())
num_list = list(map(int,input().split()))
max_list = [0 for _ in range(num)]
max_list[0] = num_list[0]
max_sum = max_list[0]
end = max_list[0]
end_index = 0
for i in range(1, num):
max_list[i] = max(num_list[i], max_list[i-1]+num_list[i])
if max_list[i] > max_sum:
max_sum = max_list[i]
end = num_list[i]
end_index = i
temp = 0
for i in range(end_index,-1,-1):
temp += num_list[i]
if temp == max_sum:
start = num_list[i]
break
if max_sum < 0:
print(0, num_list[0], num_list[-1])
else:
print(max_sum, start, end)