Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 * 1041 <= nums[i] < 2161 <= k <= floor(nums.length / 3)Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Sliding Window
[1,2,1,2,6,7,5,1] 2
[1,2,1,2,1,2,1,2,1] 2
best-time-to-buy-and-sell-stock-iii)sum-of-variable-length-subarrays)maximize-ysum-by-picking-a-triplet-of-distinct-xvalues)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #689: Maximum Sum of 3 Non-Overlapping Subarrays
class Solution {
public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
int[] ans = new int[3];
int s = 0, s1 = 0, s2 = 0, s3 = 0;
int mx1 = 0, mx12 = 0;
int idx1 = 0, idx121 = 0, idx122 = 0;
for (int i = k * 2; i < nums.length; ++i) {
s1 += nums[i - k * 2];
s2 += nums[i - k];
s3 += nums[i];
if (i >= k * 3 - 1) {
if (s1 > mx1) {
mx1 = s1;
idx1 = i - k * 3 + 1;
}
if (mx1 + s2 > mx12) {
mx12 = mx1 + s2;
idx121 = idx1;
idx122 = i - k * 2 + 1;
}
if (mx12 + s3 > s) {
s = mx12 + s3;
ans = new int[] {idx121, idx122, i - k + 1};
}
s1 -= nums[i - k * 3 + 1];
s2 -= nums[i - k * 2 + 1];
s3 -= nums[i - k + 1];
}
}
return ans;
}
}
// Accepted solution for LeetCode #689: Maximum Sum of 3 Non-Overlapping Subarrays
func maxSumOfThreeSubarrays(nums []int, k int) []int {
ans := make([]int, 3)
s, s1, s2, s3 := 0, 0, 0, 0
mx1, mx12 := 0, 0
idx1, idx121, idx122 := 0, 0, 0
for i := k * 2; i < len(nums); i++ {
s1 += nums[i-k*2]
s2 += nums[i-k]
s3 += nums[i]
if i >= k*3-1 {
if s1 > mx1 {
mx1 = s1
idx1 = i - k*3 + 1
}
if mx1+s2 > mx12 {
mx12 = mx1 + s2
idx121 = idx1
idx122 = i - k*2 + 1
}
if mx12+s3 > s {
s = mx12 + s3
ans = []int{idx121, idx122, i - k + 1}
}
s1 -= nums[i-k*3+1]
s2 -= nums[i-k*2+1]
s3 -= nums[i-k+1]
}
}
return ans
}
# Accepted solution for LeetCode #689: Maximum Sum of 3 Non-Overlapping Subarrays
class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
s = s1 = s2 = s3 = 0
mx1 = mx12 = 0
idx1, idx12 = 0, ()
ans = []
for i in range(k * 2, len(nums)):
s1 += nums[i - k * 2]
s2 += nums[i - k]
s3 += nums[i]
if i >= k * 3 - 1:
if s1 > mx1:
mx1 = s1
idx1 = i - k * 3 + 1
if mx1 + s2 > mx12:
mx12 = mx1 + s2
idx12 = (idx1, i - k * 2 + 1)
if mx12 + s3 > s:
s = mx12 + s3
ans = [*idx12, i - k + 1]
s1 -= nums[i - k * 3 + 1]
s2 -= nums[i - k * 2 + 1]
s3 -= nums[i - k + 1]
return ans
// Accepted solution for LeetCode #689: Maximum Sum of 3 Non-Overlapping Subarrays
struct Solution;
impl Solution {
fn max_sum_of_three_subarrays(nums: Vec<i32>, k: i32) -> Vec<i32> {
let k = k as usize;
let sums: Vec<i32> = nums.windows(k).map(|w| w.iter().sum()).collect();
let n = sums.len();
let mut left = vec![];
let mut left_max = 0;
let mut left_index = 0;
for i in 0..n {
if sums[i] > left_max {
left_max = sums[i];
left_index = i;
}
left.push((left_max, left_index));
}
let mut right = vec![];
let mut right_max = 0;
let mut right_index = n;
for i in (0..n).rev() {
if sums[i] >= right_max {
right_max = sums[i];
right_index = i;
}
right.push((right_max, right_index));
}
right.reverse();
let mut mid_max = 0;
let mut res = vec![0, 0, 0];
for i in k..n - k {
let sum_3 = sums[i] + left[i - k].0 + right[i + k].0;
if sum_3 > mid_max {
mid_max = sum_3;
res = vec![left[i - k].1, i, right[i + k].1];
}
}
res.into_iter().map(|x| x as i32).collect()
}
}
#[test]
fn test() {
let nums = vec![1, 2, 1, 2, 6, 7, 5, 1];
let k = 2;
let res = vec![0, 3, 5];
assert_eq!(Solution::max_sum_of_three_subarrays(nums, k), res);
}
// Accepted solution for LeetCode #689: Maximum Sum of 3 Non-Overlapping Subarrays
function maxSumOfThreeSubarrays(nums: number[], k: number): number[] {
const n: number = nums.length;
const s: number[] = Array(n + 1).fill(0);
for (let i = 0; i < n; ++i) {
s[i + 1] = s[i] + nums[i];
}
const pre: number[][] = Array(n)
.fill([])
.map(() => new Array(2).fill(0));
const suf: number[][] = Array(n)
.fill([])
.map(() => new Array(2).fill(0));
for (let i = 0, t = 0, idx = 0; i < n - k + 1; ++i) {
const cur: number = s[i + k] - s[i];
if (cur > t) {
pre[i + k - 1] = [cur, i];
t = cur;
idx = i;
} else {
pre[i + k - 1] = [t, idx];
}
}
for (let i = n - k, t = 0, idx = 0; i >= 0; --i) {
const cur: number = s[i + k] - s[i];
if (cur >= t) {
suf[i] = [cur, i];
t = cur;
idx = i;
} else {
suf[i] = [t, idx];
}
}
let ans: number[] = [];
for (let i = k, t = 0; i < n - 2 * k + 1; ++i) {
const cur: number = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0];
if (cur > t) {
ans = [pre[i - 1][1], i, suf[i + k][1]];
t = cur;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.