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.
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Case 1: 14 1 4 Case 2: 7 1 6
这道题原先的思路是两个for循环,一看就不行,因为数据太大以至于超时。简单的方法就是减少一个for循环
就用一个for循环。在网上看了一两篇博客简单总结一下。
这道题是动态规划题,但是不用动态,也可以做出来。
思路:就是从第一个数一直累加,直到结果为负数的时候,这个时候就从下一个数为第一个数在相加,只有
当是负数的时候,代表前面的数累加的最大值达到了最大(如果再往后加就不是最大的数了),
直接跳到下一个数就行了。其中要加的一点就是记录下,起始下标就行了。还有一点要注意的就是当全部
是负数的时候,这个时候有一点坑,在代码中再讲。
int n,u=1; scanf("%d",&n); while(n--) { int m; int a[100005]; scanf("%d",&m); for(int i=0;i<m;i++) scanf("%d",&a[i]); int ma=-1001,k=0,l,s=0; //ma必须要小于-1000,因为第一个数可能是-1000,如果不是的话 int sum=0; //第一个数可能就遗漏。s是中间替换变量。作用在下面。 for(int i=0;i<m;i++) { sum+=a[i]; if(sum>ma) ma=sum,l=i,k=s;//将s的值付给k。就是刚开始的位置。 if(sum<0) sum=0,s=i+1; //假若没有中间变量,(k=i+1这是不行的)当给的数据都是负数的时候就会多加1. } printf("Case %d:\n",u++); printf("%d %d %d\n",ma,k+1,l+1); if(n!=0)
//也是一个坑点 printf("\n"); } return 0;
这道题真的适合细心的同学,如果不细心就会造成wc。