题目:
代码如下:
#include<bits/stdc++.h>
using namespace std;
#define MAX 1000005
#define NIL 1e9
typedef long long LL;
LL a[MAX];
int main()
{
LL n,sum = 0,ans = -NIL;
cin >> n;
for(int i = 0;i < n;i++) cin >> a[i];
for(int i = 0;i < n;i++) ans = max(ans,a[i]); //找寻最大的那个数
if(ans < 0) cout << ans << endl; //如果最大的数都<0,那么肯定越加越小,直接输出最大的那个数。
else{
for(int i = 0;i < n;i++){
sum += a[i];
if(sum < 0) sum = 0; //加到这个数已经<0了,还不如不加前面的数,从这个数之和开始加
ans = max(ans,sum); //挑选最大字段和
}
cout << ans << endl;
}
return 0;
}
这是一道经典的dp问题,求最大字段和。注释已经解释。