前缀和
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int num[maxn], pre[maxn] = {0};
int ext[maxn] = {0};
int main()
{
int n; scanf("%d", &n);
int cnt = 0;
for(int i = 1; i <= n; i++){
scanf("%d", &num[i]);
if(i == 0) pre[i] = num[i];
else pre[i] = pre[i-1] + num[i];
if(num[i] < 0) cnt++;
}
int Min = 1<<30;
for(int i = 0; i <= n; i++){
if(pre[i] < Min){
Min = pre[i];
ext[i] = i;
}else{
ext[i] = ext[i-1];
}
}
int Max = -1e9, l, r;
for(int i = 1; i <= n; i++){
if(pre[i]-pre[ext[i]] > Max){
Max = pre[i]-pre[ext[i]];
l = ext[i]+1, r = i;
}
}
if(cnt == n){
printf("0 %d %d\n", num[1], num[n]);
return 0;
}
if(l < r)
printf("%d %d %d\n", Max, num[l], num[r]);
else
printf("%d %d %d\n", num[l], num[l], num[l]);
return 0;
}
原文:https://www.cnblogs.com/sourcry/p/10421974.html