689 Maximum Sum of 3 Non-Overlapping Subarrays

1. Question

In a given arraynumsof positive integers, find three non-overlapping subarrays with maximum sum.

Each subarray will be of sizek, and we want to maximize the sum of all3*kentries.

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.lengthwill be between 1 and 20000.

nums[i]will be between 1 and 65535.k

will be between 1 and floor(nums.length / 3).

2. Implementation

(1) DP

思路:

  1. 利用prefixSum数组,我们可以查到任意区间(i,j)的和,按照我们构造sum数组的方法,subarray(i,j)的和是sum[j + 1] - sum[i]

  2. 我们可以利用leftIndex数组和rightIndex数组分别保存左边和右边最大subarray sum的起点,如果中间max sum subarray的区间是(i , i + k - 1), 那么左边数组的范围是(0, i - 1), 右边数组的范围(i + k, n - 1)

  3. 注意当我们求最大右区间时,当前的subarray sum如果大于等于当前最大的subarray sum,我们为了让结果lexicographically small, 我们将其放入对应rightIndex数组里,这个处理和最大左区间不同

  4. 中间区间的 i介于 (i, i + k - 1)之间,由于i + k - 1 <= n - k - 1 => i <= n - 2*k, 所以中间区间的起点在(k, n - 2 * k)

3. Time & Space Complexity

DP: 时间复杂度O(n), 空间复杂度O(n)

Last updated

Was this helpful?