题目:
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).思路:
题目要求需要找出三个不重叠的区间,使得其和最大。我们可以从中间区间入手,假如中间的区间是[i, i + k - 1],其中k <= i <= n - 2k,那么对应左侧区间的范围就是[0, i - 1],右侧区间的范围是[i + k, n - 1]。左侧区间和右侧区间的最大值就可以通过动态规划来计算出来。我们定义posLeft[i]表示在[0, i]区间内的起始索引,定义posRight[i]表示在[i, n - 1]区间内的起始索引。然后就测试所有可能的中间区间(k <= i <= n - 2k),对于每个中间区间,我们可以获得其对应的左侧区间最佳选择和右侧区间最佳选择,然后比较三个区间的和是否超过了截止目前的最大值。
注意:为了保证我们得到字典序最小的索引序列,在计算右侧区间的时候我们用 ">= tot"来判断,而在计算左侧区间的时候我们用"> tot"来判断(我在下面的代码片段中已经做了注释)。算法的时间复杂度是O(n),空间复杂度也是O(n)。
代码:
class Solution { public: vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) { int n = nums.size(), maxsum = 0; vector<int> sum = {0}, posLeft(n, 0), posRight(n, n-k), ans(3, 0); for (int i : nums) { // calculate the accumulated sum sum.push_back(sum.back() + i); } // DP for starting index of the left max sum interval for (int i = k, tot = sum[k]-sum[0]; i < n; ++i) { // caution: the condition is "> tot" for left interval, in order to get the min index if (sum[i + 1]- sum[i + 1 - k] > tot) { posLeft[i] = i + 1 - k; tot = sum[i + 1] - sum[i + 1 - k]; } else { posLeft[i] = posLeft[i - 1]; } } // DP for starting index of the right max sum interval for (int i = n - k - 1, tot = sum[n] - sum[n - k]; i >= 0; --i) { // caution: the condition is ">= tot" for right interval, in order to get the min index if (sum[i + k] - sum[i] >= tot) { posRight[i] = i; tot = sum[i + k] - sum[i]; } else { posRight[i] = posRight[i + 1]; } } // test all possible middle interval for (int i = k; i <= n - 2 * k; ++i) { int l = posLeft[i - 1], r = posRight[i + k]; int tot = (sum[i + k] - sum[i]) + (sum[l + k] - sum[l]) + (sum[r + k] - sum[r]); if (tot > maxsum) { maxsum = tot; ans = {l, i, r}; } } return ans; } };