Problem Description
Given an integer array nums and an integer k, find three non-overlapping subarrays of length k that have the maximum total sum. Return their starting indices as a list. If multiple answers exist, return the lexicographically smallest one.
Key Insights
- Use a sliding window to compute the sum of every contiguous subarray of length k.
- Precompute best left-window indices and best right-window indices for every possible middle window position.
- Use dynamic programming: • left[i] stores the index of the subarray with the maximum sum for windows ending at or before i. • right[i] stores the index of the subarray with the maximum sum for windows starting at or after i.
- Iterate over all possible middle subarray positions and combine with left and right indices to get the overall maximum sum while ensuring non-overlap.
- Choosing indices with strict comparisons will naturally cater to the lexicographical requirement.
Space and Time Complexity
Time Complexity: O(n) – where n is the length of nums, since we scan the array a constant number of times. Space Complexity: O(n) – used for storing window sums and the left/right index arrays.
Solution
We first calculate the sum for every window of length k using a sliding window technique. Next, we build two auxiliary arrays: • The left array holds at each position the best starting index for a window on the left side. • The right array holds at each position the best starting index for a window on the right side. Then, for each possible middle window, we determine the best left and right windows and update the result if a higher total sum is achieved. This method ensures non-overlapping intervals and the lexicographically smallest result in case of ties.