Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } 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、暴力搜索
O(N2)的时间复杂度,K<10000,不超时
int sum = 0, mx = -INF, s, t; for (int i=0; i) { sum = 0; for (int j=i; j ) { sum += n[j]; if (sum > mx) { mx = sum; s = i;t = j; } } } printf("%d %d %d", mx,n[s], n[t]);
思路2、扫描
经典DP问题, 基于这样一个事实:保存一个最大字段和以及一个当前子段和, 如果当前字段和大于当前最大字段和, 那么更新这个最大字段和, 如果当前字段和为负数的时候, 直接把当前字段和甚设置成0, 求最大字段和算法如下:
int MaxSum(int A[], int N) { int currentSum = 0; int maxSum = 0; for(int i = 0; i < N; ++i) { currentSum += A[i]; if(currentSum > maxSum) maxSum = currentSum; else if(currentSum < 0) currentSum = 0; } return maxSum; }
由于这个题目里面还需要保存最大子段和的第一个和第二个元素, 加一些额外的变量记录以及在对应的更新maxSum和把currentSum设置成0的时候对应进行维护就行了. 算法复杂度O(N)
注意点:
当序列中有0但是其他都是负数的时候, 不是输出真个序列的第一个和最后一个元素,而是输出第一个0. 比如3 -1 0 -1 应当输出 0 0 0