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
solution:
#include<bits/stdc++.h>
using namespace std;
bool allnega(vector<int>a)
{
for(int i=1;i<a.size();i++)
{
if(a[i]>=0)return false;
}
return true;
}
int main()
{
int k;cin>>k;
vector<int>a(k+1);
for(int i=1;i<=k;i++)cin>>a[i];
int maxans=0;
vector<int>pre(k+1,0);
pre[0]=-1;
int tmp;
int ansl=0,ansr=0;
if(allnega(a))
{
cout<<0<<' '<<a[1]<<' '<<a[k]<<endl;
return 0;
}
else
{
for(int i=1;i<=k;i++)
{
pre[i]=max(pre[i-1]+a[i],a[i]);
if(pre[i-1]<0)
{
tmp=a[i];
}
if(pre[i]>maxans)
{
ansr=a[i];
ansl=tmp;
}
maxans=max(maxans,pre[i]);
}
cout<<maxans<<' '<<ansl<<' '<<ansr<<endl;
}
}
测试点3:只有一个数字。
求最大子序列和以及左右边界数字。
题目自带条件:所有数字均为负数时特判。这个条件如果不存在,上述在仅有一个负数时会产生错误,虽然不影响这道题但是待解决。即maxans初始化为0导致的需要初始化为a[0],这样能保证稳定求出最大值。但是如果初始化为a[0]上述无法解决左右边界问题,看了其他题解不少也存在这个问题。插眼