Skip to content

Latest commit

 

History

History

689

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.

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 1:

Input: nums = [1,2,1,2,6,7,5,1], k = 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.

Example 2:

Input: nums = [1,2,1,2,1,2,1,2,1], k = 2
Output: [0,2,4]

 

Constraints:

  • 1 <= nums.length <= 2 * 104
  • 1 <= nums[i] < 216
  • 1 <= k <= floor(nums.length / 3)

Companies:
Facebook

Related Topics:
Array, Dynamic Programming

Similar Questions:

Solution 1. Prefix Sum + Mono-stack

// OJ: https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    vector<int> maxSumOfThreeSubarrays(vector<int>& A, int k) {
        int N = A.size(), M = N - k + 1, maxSum = 0;
        vector<int> sum(M);
        for (int i = 0, a = 0, b = 0; i < N; ++i) {
            a += A[i];
            if (i - k >= 0) b += A[i - k];
            if (i - k + 1 >= 0) sum[i - k + 1] = a - b;
        }
        stack<int> s;
        for (int i = M - 1; i >= 2 * k; --i) {
            if (s.empty() || sum[i] >= sum[s.top()]) s.push(i);
        }
        vector<int> ans;
        for (int i = k, left = 0; i < M - k; ++i) {
            if (sum[i - k] > sum[left]) left = i - k;
            int val = sum[left] + sum[i] + sum[s.top()];
            if (val > maxSum) {
                maxSum = val;
                ans = {left, i, s.top()};
            }
            if (i + k == s.top()) s.pop();
        }
        return ans;
    }
};