1
来源:互联网 发布:cdn网络节点 编辑:程序博客网 时间:2024/06/06 07:39
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.
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
Case 1:14 1 4Case 2:7 1 6
#include<stdio.h>int main(){ int t,n,tt=1; scanf("%d",&t); while(t--) { scanf("%d",&n); //尺取法 int maxx=-1001,sum=0,l=1,left,right,x; for(int i=1;i<=n;i++) { scanf("%d",&x); sum+=x; if(sum>maxx) { maxx=sum; left=l;//更新起点 right=i;//更新终点 } if(sum<0)//顺序不能反,考虑如果一组数全是负数 { sum=0;//如果当前的累加和已经小于0则抛弃这一段重新开始 l=i+1; } } printf("Case %d:\n",tt++); printf("%d %d %d\n",maxx,left,right); if(t) printf("\n"); } return 0;}
阅读全文