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
参考代码:
#include<stdio.h>
int main()
{
/*m,n表示最大子序列的左右边界,
cnt1表示负数个数,cnt2表示非正数个数*/
int i,k,m,n,cnt1,cnt2;
cnt1=cnt2=0;
scanf("%d",&k);
int a[k];
int thisSum=0,maxSum=0;
for(i=0;i<k;i++)
{
scanf("%d",&a[i]);
if(a[i]<=0)
{
if(a[i]<0)
{
cnt1++;
}
cnt2++;
}
thisSum+=a[i];
if(thisSum>maxSum)
{
maxSum=thisSum;
n=i; //记录最大子序列的右边界
}
else if(thisSum<0)
{
thisSum=0;
}
}
printf("%d ",maxSum);
if(cnt1==k)
{
printf("%d %d",a[0],a[k-1]);
}
else if(cnt2==k)
{
printf("0 0");
}
else
{
int t=0;
for(i=n;i>=0;i--)
{
t+=a[i];
if(t==maxSum)
{
m=i;
}
}
printf("%d %d",a[m],a[n]);
}
return 0;
}
提交结果:
思路:
-
通过在线处理可以很容易得到最大子序列和及其右边界;
-
根据最大子序列和和右边界从右边界开始反向遍历数组找到左边界,这里反向找左边界一定要遍历到底(即数组开始的位置),因为这个问题,一开始最大和前面有一段是0这个测试点一直没通过,我当时的思路是找到最大左边界,如果最大左边界前面一段是0,就把左边界改为0,但是仍然没有通过,后来想到一种情况1 -1 0 0 2 3,如果按照上面的思路应该输出5 0 3,但实际应该是5 1 3。
注: 序列全是负数和序列是负数和0我这里是单独去处理的。
- 如果序列全是负数,题目中要求如果所有的K数都是负的,那么它的最大和被定义为0,你应该输出整个序列的第一个和最后一个数;
- 如果序列是负数和0,直接输出0 0 0即可。