问题:
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
给你一串数字,要求求其和最大的子序列(连续的),最后输出该子序列的起始坐标,以及最大的和。
另:每个序列最多有100000个整数,整数的范围是[-1000,1000]。
代码:
#include <stdio.h>
#include <stdlib.h>
int a[100000];
int main()
{
int T,N,i,max,end,start,t,count=1;
long sum;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
sum=0;
start=end=t=1;
max=-1001;
for(i=0;i<N;){
scanf("%d",&a[i]);
sum+=a[i];
i++;
if(sum>max){
max=sum;
start=t;
end=i;
}
if(sum<0){
t=i+1;
sum=0;
}
}
printf("Case %d:
",count++);
printf("%d %d %d
",max,start,end);
if(T>0) printf("
");
}
return 0;
}
红色部分是用来找到和最大子序列的开端坐标与结尾坐标。试想如果前一段子序列的和小于0,则该段子序列完全可以丢掉 ,即“潜在和最大子序列”的开端坐标变为该总和为负的子序列的下一个坐标;而结束坐标便是最后一个令sum>max的整数的坐标。