51Nod - 1049 最大子段和问题(DP)

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

状态转移方程: dp[i] = max(dp[i-1]+a[i],dp[i]);用maxx标记一下,找出最大的子段和。

#include<bits/stdc++.h>
using namespace std;
#define LL long long

const int MAXN = 1e5+10;
const int INF = 0x3f3f3f3f;
const int N= 1010;
const int MOD = 0x3f3f3f3f;


LL n,a[MAXN];
LL dp[MAXN];
int main(){
    while(scanf("%lld",&n)!=EOF){
        memset(a,0,sizeof(a));
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i]);
        }
        dp[0] = 0;
        LL maxx = 0;
        for(int i=1;i<=n;i++){
            dp[i] = max(dp[i-1]+a[i],a[i]);
            maxx = max(maxx,dp[i]);
        }
        cout<<maxx<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/l18339702017/article/details/81178907