N个整数组成的序列a11,a22,a33,…,ann, 求该序列如aii+ai+1i+1+…+ajj的连续子段和的最大值。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
Input
第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N + 1行:N个整数(-10^9 <= Aii <= 10^9)
Output
输出最大子段和。
Sample Input
6 -2 11 -4 13 -5 -2
Sample Output
20
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
const int M=50000+10;
ll a[M],dp[M];
int main()
{
int n,flag=0;
cin>>n;
memset(a,0,sizeof(a));
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
cin>>a[i];
if(a[i]>=0) flag=1;
}
ll s=0;
if(flag==0) cout<<0<<endl;
else
{
for(int i=1;i<=n;i++){
if(dp[i-1]>=0) {
dp[i]=dp[i-1]+a[i];
}
else dp[i]=a[i];
s=max(s,dp[i]);
}
}
cout<<s<<endl;
return 0;
}