洛谷P1115 最大子段和【dp】

题目描述

给出一段序列,选出其中连续且非空的一段使得这段和最大。

输入输出格式

输入格式:

第一行是一个正整数NN,表示了序列的长度。

第二行包含NN个绝对值不大于1000010000的整数A_iAi​,描述了这段序列。

输出格式:

一个整数,为最大的子段和是多少。子段的最小长度为11。

输入输出样例

输入样例#1: 复制

7
2 -4 3 -1 2 -4 3

输出样例#1: 复制

4

说明

【样例说明】

2,-4,3,-1,2,-4,32,−4,3,−1,2,−4,3中,最大的子段和为4,该子段为3,-1,23,−1,2.

【数据规模与约定】

对于40%的数据,有N ≤ 2000N。

对于100%的数据,有N ≤ 200000。

#include<cstdio>
#include<queue>
#include <iostream>
using namespace std;
const int maxn=200005;
int a[maxn];
int maxsubseqsum(int a[],int n)
{
    int maxSum=a[0],thisSum=a[0];
    for(int i=1;i<n;++i)
    {
        thisSum+=a[i];
        if(thisSum>maxSum)
            maxSum=thisSum;
        else if(thisSum<0)
            thisSum=0;
    }
    return maxSum;
}


int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;++i)
        scanf("%d",&a[i]);
    printf("%d
",maxsubseqsum(a,n));
    return 0;
}
原文地址:https://www.cnblogs.com/aerer/p/9930945.html