原题链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1049
思路:O(n)边读入边处理,如果前面的子段和大于0,那么就用当前的加上前面的,否则就是当前的,并随时更新最大和就是
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAXN = 1e4 + 5;
const double eps = 1e9;
typedef long long LL;
int main() {
int n, a;
scanf("%d", &n);
long long sum = 0,maxv=0;
for (int i = 0; i < n; i++) {
scanf("%d", &a);
if (sum < 0)sum = 0;
sum += a;
maxv = max(maxv,sum);
}
printf("%lld\n", maxv);
return 0;
}