PAT 1007 Maximum Subsequence Sum 最大连续子序列和

Given a sequence of K integers { N1, N2, …, NK }. A continuous subsequence is defined to be { Ni, Ni+1, …,Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has thelargest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the

largest sum being 20.Now you are supposed to find the largest sum, together with the first and the last numbers of the
maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of themaximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4
 
题目意思:求最⼤连续⼦序列和,输出最⼤的和以及这个⼦序列的开始值和结束值。如果所有数都⼩于0,那么认为最⼤的和为0,并且输出⾸尾元素。
解题思路:最开始的思路就是直接两层循环,设置i和j两个指针直接来定位求和,但是后来发现,其实可以直接使用一层循环,因为所求的和一般情况下必然是正数,除非全都是负数。但如果一开始就将全是负数的情况剔除后,只用一层循环便可以,一旦求和的结果是负数,那么起始定位的指针i便从其后重新取。
#include<cstdio>
#include<cstring>
#include<algorithm>
#define inf 0x7fffffff
using namespace std;

int a[10010];
int main()
{
    int n,i,left,right,ans=0,l=1;
    int maxs=-inf;
    int flag=0;
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    {
        scanf("%d",&a[i]);
        if(a[i]>=0)
        {
            flag=1;
        }
    }
    if(flag==0)//全部为负数的情况
    {
        printf("%d %d %d\n",ans,a[1],a[n]);
        return 0;
    }
    for(i=1; i<=n; i++)
    {
        ans+=a[i];
        if(ans<0)
        {
            ans=0;
            l=i+1;
        }//直到连续子序列出现正数
        else if(ans>maxs)//更新最大连续子序列
        {
            maxs=ans;
            left=l;
            right=i;
        }
    }
    printf("%d %d %d\n",maxs,a[left],a[right]);
    return 0;
}

 

posted @ 2019-06-22 13:51  王陸  阅读(526)  评论(0编辑  收藏  举报