Maximum Subsequence Sum
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.
Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4
思路:题意是输出最大连续子列和并输出最大连续子列和的第一个元素和最后一个元素。当其序列全为负数时,输出0并输出序列的第一个元素和最后一个元素。这道题的解法类似之前那道求最大子列和,只不过这题多了要输出连续子列和的第一个元素和最后一个元素。解这道题还是采用更新sum的方法,当sum小于0时重置sum,因为sum小于0的时候只会使后面的子列和更小。然后当sum大于前面的最大值(Max)时,更新sum,同时记录现在的下标。这道题还是用在线处理的方法,通过更新ThisSum的值,当ThisSum小于0时将其值重置为0,因为当ThisSum为负数时只会使后面的子列和变小。当ThisSum>MaxSum时,将ThisSum赋值给MaxSum,同时记录下标。当遍历完序列后,前面记录的下标就是最大连续子列和最后一个元素的下标。然后可以再从这个元素往前遍历,当其等于前面的MaxSum的时候,说明找到了最大连续子列和的第一个元素。这里要注意,前面有可能会有一部分的0,所以不能直接break。
代码:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n],i,j=0,ThisSum = 0,MaxSum = 0,flag = 0,k = 1;
for(i = 0;i < n;i++)
cin >> a[i];
for(i = 0; i < n;i++)//在线处理方法
{
ThisSum += a[i];
if(ThisSum > MaxSum){
MaxSum = ThisSum;
k = i;//记录子序列最后一个元素下标
}
if(ThisSum < 0){
ThisSum = 0;
}
if(a[i] >= 0){
flag = 1;
}
}
ThisSum = 0;
for(i = k; i >= 0;i--)//反向遍历,求得子序列第一个元素的下标
{
ThisSum +=a[i];
if(ThisSum == MaxSum)
j = i;
}
if(MaxSum)
{
cout << MaxSum << " " << a[j] << " "<< a[k] << endl;
}
else if(flag)
{
cout << 0 <<" "<< 0 <<" "<< 0 << endl;
}
else
{
cout << 0 << " " << a[0] << " " << a[n-1] << endl;
}
return 0;
}