hdu 1003 Max Sum

Problem Description
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
给你一些数字求出一个连续和最大的串 输出最大值
 
用两个指针指向我们的这个数组(l1  r1 表示 左指针和右指针 )
当这个数之前的和 < 0时 将我们的左指针指向这个数的下一个数
有指针一直跟着数组一直往下走
然后当我们的sum > max
那么改变我们的max 和  我们的左右指正( l , r  )
 
代码见下:
#include <stdio.h>

int a[100005];

int main()
{
    int n;
    int k = 1;
    scanf("%d",&n);
    while(n--)
    {
        int m;
        scanf("%d",&m);
        int i = 0;
        for(i = 1; i <= m; i++)
            scanf("%d",&a[i]);

        int max = -100000;
        int l= 1,r= 1,l1 = 1,r1 = 1;
        int sum = 0;

        for(i = 1; i <= m; i++)
          {
              int flag = 0;

              sum+=a[i];

             r1 = i;

              if(sum > max)
                {
                    max = sum;
                    r =r1;
                    l = l1;
                }
              if(sum < 0)
                {
                    l1 = i+1;
                    flag = 1;
                }

                /*printf("%d   %d %d\n",l,r,sum);*/
            if(flag) sum = 0;
          }

          printf("Case %d:\n",k++);
        if(n>=1)
            printf("%d %d %d\n\n",max,l,r);
        else
            printf("%d %d %d\n",max,l,r);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yyroom/p/2997167.html