题意:求最大连续子序列的和。
题目链接:https://www.patest.cn/contests/pat-a-practise/1007
分析:
1、预处理前缀和;
2、统计截止到每一个i时最小的前缀和(sum[id]);
3、比较每一个连续子序列(id+1, i)即可得最大值。
#include<bits/stdc++.h> using namespace std; const int MAXN = 10000 + 10; int a[MAXN]; int sum[MAXN]; int main(){ int n; scanf("%d", &n); bool ok = false; sum[0] = 0; for(int i = 1; i <= n; ++i){ scanf("%d", &a[i]); sum[i] = a[i] + sum[i - 1]; if(a[i] >= 0) ok = true; } if(!ok){ printf("0 %d %d ", a[1], a[n]); return 0; } int mi = 0; int ans = -1000000000; int st = 1, et; int id = a[1]; for(int i = 1; i <= n; ++i){ if(sum[i] - mi > ans){ ans = sum[i] - mi; st = id; et = a[i]; } if(sum[i] < mi){ mi = sum[i]; id = a[i + 1]; } } printf("%d %d %d ", ans, st, et); return 0; }