Problem Description
Given a sequencea[1],a[2],a[3]......a[n], your job is to calculate the max sum of asub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains aninteger T(1<=T<=20) which means the number of test cases. Then T linesfollow, each line starts with a number N(1<=N<=100000), then N integersfollowed(all the integers are between -1000 and 1000).
Output
For each test case, you should outputtwo lines. The first line is "Case #:", # means the number of thetest case. The second line contains three integers, the Max Sum in thesequence, the start position of the sub-sequence, the end position of the sub-sequence.If there are more than one result, output the first one. Output a blank linebetween two cases.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
求最大子列;
如果一个数列,全是负数,那么最大子列就是最大的那个负数;如-5 -7 -6 -3 -8 最大子列为-3
那么将该子列 -5 -7 -6 -3 -8与正子列合并 -5 -7 -6 -3 -8 2 5,我们知道最大子列为2 5
那么-57 2 3 -8 9呢 应该舍弃-5这个子列从第一个非负数开始 7 2 3 -8 9
5 -76 3 2呢 要舍弃5 -7这个子列
求解方案:
将数列从左到右依个分为多个子列,例如-5 7 2 3 -8 9分为
-5; -5 7; -5 7 2; -5 7 2 3;等
子列为负子列,去除该子列,将剩余的数列依个分为多个子列
代码如下:
#include<stdio.h>
intmain()
{
int i, j, t;
intn, number, max, sum, start, end, tempStart; //tempStart用来更新start,max当前最大子列,sum子列和
while(scanf("%d", &t) !=EOF){
for (i = 1; i <= t; i++)
{
max = -1005; //初定义max=-1005 < -1000
sum = 0;
tempStart = 1;
scanf("%d",&n);
for (j = 1; j <= n; j++)
{
scanf("%d",&number);
sum += number;
if (sum > max)
{
max = sum; //更新最大子列
start =tempStart;
end = j;
}
if (sum < 0) //前面的子列和为负数,则重新开始一条子列
{
sum = 0;
tempStart = j+ 1;
}
}
printf("Case%d:\n", i);
printf("%d %d%d\n", max, start, end);
if (i < t)
printf("\n");
}
}
}