// 前缀和(通过11/12组样例) #include <bits/stdc++.h> using namespace std; const int N = 1000010; int a[N]; int s[N]; int main(){ int n; while (scanf("%d", &n) != EOF){ for (int i=0; i<=n; i++){ s[i] = 0; } for (int i=1; i<=n; i++){ scanf("%d", &a[i]); } for (int i=1; i<=n; i++){ s[i] = s[i-1] + a[i]; } int maxx = -1e9; for (int i=1; i<=n; i++){ for (int j=i; j<=n; j++){ if (s[j] - s[i-1] > maxx){ maxx = s[j] - s[i-1]; } } } printf("%d\n", maxx); } return 0; }
贪心
#include <bits/stdc++.h> using namespace std; int main(){ int n; while (cin >> n){ int maxx = -1e9, s = 0; for (int i=0; i<n; i++){ int x; scanf("%d", &x); sum += x; if (s > maxx) maxx = s; if (s < 0) s = 0; } printf("%d\n", maxx); } return 0; }
```