51nod 1049 最大子段和

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
 收藏
 关注
N个整数组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续子段和的最大值。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
Input
第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N + 1行:N个整数(-10^9 <= A[i] <= 10^9)
Output
输出最大子段和。
Input示例
6
-2
11
-4
13
-5
-2
Output示例
20

#include <iostream>

using namespace std;
const int maxn=5e4+10;
int a[maxn];
int main()
{
    int n;
    scanf("%d",&n);
    long long sum=0,maxs=-1;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        if(sum>=0)
            sum+=a[i];
        else
            sum=a[i];
        if(sum>maxs)
            maxs=sum;
    }
    printf("%lld\n",maxs);

    return 0;
}



posted @ 2017-09-22 00:04  Bryce1010  阅读(67)  评论(0编辑  收藏  举报