基准时间限制: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;
long long A[50005],n;
long long DP[5005];
int main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=0;i<n;i++)
cin>>A[i];
long long m=-99999999;
DP[0]=A[0];
for(int i=1;i<n;i++)
{
if(A[i]+DP[i-1]<A[i])
{
DP[i]=A[i];
}
else
{
DP[i]=DP[i-1]+A[i];
}
if(DP[i]>m) m=DP[i];
}
cout<<m<<endl;
return 0;
}