https://codility.com/demo/take-sample-test/max_double_slice_sum
两个最大子段和相拼接,从前和从后都扫一遍。注意其中一段可以为0。还有最后和最前面一个不可能取到~
#include <vector> using namespace std; int solution(vector<int> &A) {
vector<int> maxEnd;
maxEnd.resize(A.size());
maxEnd[0] = 0;
for (int i = 1; i < A.size(); i++) {
maxEnd[i] = max(0, maxEnd[i - 1] + A[i]);
}
vector<int> maxBegin;
maxBegin.resize(A.size());
maxBegin[A.size() - 1] = 0;
for (int i = A.size() - 2; i >= 0; i--) {
maxBegin[i] = max(0, maxBegin[i + 1] + A[i]);
}
int result = maxEnd[0] + maxBegin[2];
for (int i = 0; i + 2 < A.size(); i++) {
int current = maxEnd[i] + maxBegin[i + 2];
result = max(result, current);
}
return result;
}