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
看到这题时候,我兴奋得一匹,嘿嘿,我他喵做过,不仅做过,我他喵还记得。一顿劈劈啪啪之后,用例4、5不过。。。
又看了一下题,他喵原来全负数时候需要特殊输出,这简单,又一顿啪啪啪,用例5还是不过。。。百思不得其解 again,再次百度,然后看到有大神说,但数组中有0且其它数是负数时候,需要输出 0 0 0,例如 4 -3 -2 0 -1,要输出0 0 0。
这他喵就很尴尬了,我觉得我是如何都不会想到这层的。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define INF 0x3f3f3f
int main()
{
int num;
int begin, end, MBegin, MEnd;
int sum, max;
int i, j;
bool allNegative = true;
scanf("%d", &num);
int a[num];
for(i=0; i<num; i++)
{
scanf("%d", &a[i]);
}
begin = end = MBegin = MEnd = 0;
sum = max = -INF;
for(i=0; i<num; i++)
{
if(a[i]>=0)
{
allNegative = false;
}
if(sum<0)
{
begin = i;
end = i;
sum = a[i];
}
else
{
sum += a[i];
end = i;
}
if(sum>max)
{
max = sum;
MBegin = begin;
MEnd = i;
}
}
if(allNegative == true)
{
max = 0;
MBegin = 0;
MEnd = num-1;
}
printf("%d %d %d\n", max, a[MBegin], a[MEnd]);
return 0;
}