Maximum Sum of 3 Non-Overlapping Subarrays - Problem
You're given an integer array nums and an integer k. Your task is to find three non-overlapping subarrays of length k that have the maximum total sum.
Return the result as a list of starting indices (0-indexed) of these three subarrays. If multiple valid answers exist with the same maximum sum, return the lexicographically smallest one.
Key constraints:
- The three subarrays cannot overlap
- Each subarray must have exactly
kelements - You need the indices of where each subarray starts
- Prefer smaller indices when there are ties
Example: For nums = [1,2,1,2,6,7,5,1] and k = 2, the answer is [0,3,5] because subarrays [1,2], [2,6], and [7,5] give the maximum sum of 22.
Input & Output
example_1.py — Basic Case
$
Input:
nums = [1,2,1,2,6,7,5,1], k = 2
›
Output:
[0, 3, 5]
💡 Note:
Subarrays [1,2] at index 0 (sum=3), [2,6] at index 3 (sum=8), and [7,5] at index 5 (sum=12) give maximum total sum of 23.
example_2.py — Tie Breaking
$
Input:
nums = [1,2,1,2,1,2,1,2,1], k = 2
›
Output:
[0, 2, 4]
💡 Note:
Multiple combinations give the same sum, but [0,2,4] is lexicographically smallest. Subarrays [1,2], [1,2], [1,2] each sum to 3, total = 9.
example_3.py — Minimum Length
$
Input:
nums = [4,3,2,1,7,6], k = 1
›
Output:
[0, 4, 5]
💡 Note:
With k=1, we pick individual elements. Elements 4, 7, 6 at indices [0,4,5] give maximum sum of 17.
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- 1 ≤ nums[i] ≤ 106
- 1 ≤ k ≤ floor(nums.length / 3)
- The array must have space for at least 3 non-overlapping subarrays of length k
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Block Values
Determine the total value of each possible k-seat block using sliding window
2
Precompute Left Options
For each position, know the best left block that doesn't interfere
3
Precompute Right Options
For each position, know the best right block that doesn't interfere
4
Optimize Middle Block
Try each middle block and combine with precomputed optimal left/right blocks
Key Takeaway
🎯 Key Insight: By precomputing the optimal left and right subarray positions for each index, we transform a cubic time problem into a linear one. The middle position iteration becomes the only variable, while left and right positions are optimally determined through dynamic programming.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code