This is an implicit sliding window problem. It is almost the same as buying and selling the stock 3.
The idea is that we gonna set up a middle line, and the line would keep moving forward. When is it moving, we would see if there is any better option for the answer.
The left side of the middle line is the first subarray, and the right side of the middle line is the second subarray. When the line is moving, a new element would be added to the left-hand side, we would check if it would increase the sum of the first subarray or not, if it cannot, we just skip. For the right-hand side, there also is a new element coming in, we need to check if it would increase the sum of the second subarray or not.
We need to query the sum of a subarray often to precalculate the prefix sum and make this query O(1).
class Solution {
public:
int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {
int n = nums.size();
vector<int> prefixSum(n + 1, 0);
prefixSum[1] = nums[0];
for(int i = 2; i <= n; i++)prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
int sumL = 0;
int res = 0;
for(int i = firstLen; i + secondLen - 1 < n; i++){
sumL = max(sumL, prefixSum[i] - prefixSum[i - firstLen]);
res = max(res, sumL + prefixSum[i + secondLen] - prefixSum[i]);
}
int sumM = 0;
for(int i = secondLen; i + firstLen - 1 < n; i++){
sumM = max(sumM, prefixSum[i] - prefixSum[i - secondLen]);
res = max(res, sumM + prefixSum[i + firstLen] - prefixSum[i]);
}
return res;
}
};