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 -21Sample Output:
10 1 4
给出一个整数序列,求出使得和最大的子序列(子序列的索引值是连续的),输出所求得的最大和,子序列的第一个数和最后一个数。如果序列全都是负数,则直接输出0,第一个数和最后一个数。这里先求出第一个数字到第n个(n=0,1,2...K,0代表0个数相加)数字的和part_sum[n],然后part_sum[i]-part_sum[j]就代表第i+1个数加到第j个数的和。然后全部比较之后就能得到结果。
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int>vec(n);
vector<int>part_sum(n+1,0);
bool isAllNeg=true;
for(int i=0;i<n;i++)
{
cin>>vec[i];
if(vec[i]>=0) isAllNeg=false;
part_sum[i+1]=part_sum[i]+vec[i];
}
if(isAllNeg)
{
cout<<0<<" "<<vec[0]<<" "<<vec[n-1];
return 0;
}
int MAX=0x80000000,left,right;
for(int i=0;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(part_sum[j]-part_sum[i]>MAX)
{
MAX=part_sum[j]-part_sum[i];
left=i;right=j;
}
}
}
cout<<MAX<<" "<<vec[left]<<" "<<vec[right-1];
}