mixsum

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. 
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000). 
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, 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 line between 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
 
 
这道题原先的思路是两个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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值