689. Maximum Sum of 3 Non-Overlapping Subarrays
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.
Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example:
Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
Note:
- nums.length will be between 1 and 20000.
- nums[i] will be between 1 and 65535.
- k will be between 1 and floor(nums.length / 3).
方法1: dynamic programming
grandyang:https://www.cnblogs.com/grandyang/p/8453386.html
思路:
易错点:
- 由于题目中还要求了必须在多种最优下选择lexicographically larger one,所以在选择是否更新左右最大的时候等号选择不同。
class Solution {
public:
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
int n = nums.size();
vector<int> sum(n + 1, 0);
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + nums[i];
vector<int> posLeft(n, 0), posRight = posLeft;
int total = sum[k] - sum[0];
// find the left hand side max position
// start from 0 to n - k
for (int i = k; i < n; i++) {
if (sum[i + 1] - sum[i + 1 - k] > total) {
total = sum[i + 1] - sum[i + 1 - k];
posLeft[i] = i + 1 - k;
}
else {
posLeft[i] = posLeft[i - 1];
}
}
// find the right hand side max position
// start from 0 to n - k
posRight[n - k] = n - k;
total = sum[n] - sum[n - k];
for (int i = n - k - 1; i >= 0; i--) {
if (sum[k + i] - sum[i] >= total) {
total = sum[k + i] - sum[i];
posRight[i] = i;
}
else {
posRight[i] = posRight[i + 1];
}
}
// test all middle interval
int maxsum = 0;
vector<int> result(3, 0);
for (int i = k; i < n - 2 * k + 1; i++) {
int l = posLeft[i - 1], r = posRight[i + k];
int total = (sum[i + k] - sum[i]) + (sum[l + k] - sum[l]) + (sum[r + k] - sum[r]);
if (total > maxsum) {
maxsum = total;
result[0] = l; result[1] = i; result[2] = r;
}
}
return result;
}
};