很好的思路,同时从前面和后面计算最大的连续序列和,然后遍历中间点,得出最大值。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<functional>
#include<vector>
#include<string.h>
using namespace std;
const int MAXSIZE = 50002;
const int INF = 0x3f3f3f3f;
int a[MAXSIZE];
int s[MAXSIZE];
int e[MAXSIZE];
int n;
int main() {
// freopen("in.txt", "r", stdin);
int testcase;
scanf("%d", &testcase);
while(testcase--) {
scanf("%d", &n);
for (int i = 0; i<n; i++) {
scanf("%d", &a[i]);
}
int sum = 0;
int res = a[0];
s[0] = a[0];
for (int i = 0; i< n; i++) {
sum += a[i];
if (sum>res) {
res = sum;
}
if (sum < 0) {
sum = 0;
}
s[i] = res;
}
sum = 0;
res = a[n-1];
e[n-1] = res;
for (int i = n-1; i>=0; i--){
sum += a[i];
if (sum>res){
res = sum;
}
if (sum < 0){
sum = 0;
}
e[i] = res;
}
res = -INF;
for (int i = 0; i<n-1; i++){
res = max(res, s[i]+e[i+1]);
}
cout<<res<<endl;
}
}