Maximum Sum of 3 Non-Overlapping Subarrays
Pick three separate runs of k numbers with the largest total, by fixing the middle run and taking the best run on each side.
You are given an array of positive integers numskkk3k
If several choices give the same largest sum, return the one that comes first when the lists are compared like words in a dictionary. The smallest first index wins, and on a tie the smallest second index, then the third.
Example 1
Output: [0, 3, 5]
Explanation: the subarrays [1, 2], [2, 6] and [7, 5] add up to 23. Starting the first one at index 1, [2, 1], gives the same 23, but [0, 3, 5] comes before [1, 3, 5].
Example 2
Output: [0, 2, 4]
Explanation: any two neighbors add up to 3, so every valid choice sums to 9, and [0, 2, 4] comes first.
The Idea
Think of numsk
A run of kkk = 2
The obvious move is to grab the biggest window first: 13, which starts at index 4 and covers 6 and 7. But it uses up indexes 4 and 5, so the windows that start at 3 and at 5 can no longer be picked. The best that is left is a 3 on the left and the 6 at index 6, for a total of 22. The answer, 23, does not use the 13 at all.
So the biggest window can get in the way of its neighbors, and the three windows have to be chosen together. Trying every set of three is slow, though. Is there a way to choose one window and let the other two follow?
There is, if the one we choose is the middle window. Once the middle window is fixed, the left window only has to end before it, and the right window only has to start after it. The two sides no longer affect each other, so on each side we simply take the best window there. Look at the picture below.
The top row is nums
If, for every index, we know in advance the best window that starts at or before it and the best window that starts at or after it, each middle window costs only two lookups and two additions. Keeping a running best from the left and another from the right like this is often called a prefix maximum and a suffix maximum.
Solution Approach
Turning the middle-window idea into code means settling four things: how to get every window sum quickly, which middle windows to try, how to find the best window on each side, and how to break ties.
Adding up every window
How do we get all the window sums? Adding k
The window that starts at index 3 holds 2 and 6, so its sum is 8. The window that starts at index 4 gains 7 on the right and loses 2 on the left, so its sum is 8 + 7 - 2 = 13. Each step costs one addition and one subtraction, however large k
Choosing the middle window
Why not try every set of three windows? With 1,000 possible starts there are about 166 million such sets, and each needs a check that the windows do not overlap. Fixing the middle window leaves a single loop over its start, called mid
Which values can midk - 1midkmid + kmid
The best window on each side
How do we know the best window on each side without searching it every time? Build two arrays first. left[i]iileft[i - 1]
right[i]imidleft[mid - k]right[mid + k]left[1] = 0right[5] = 5
Breaking ties
When windows have equal sums, which one do we keep? The answer must come first in dictionary order, so on every tie we keep the earlier start. left
rightmid
Java Solution
The method maxSumOfThreeSubarrays
- First, set
to the length ofn andnums , the number of possible window starts, and fill the arraym = n - k + 1 in one loop overwindow . A running total,nums , addssum , dropsnums[i] once the window is full, and is stored innums[i - k] .window[i - k + 1] - Fill the array
in a loop from left to right.left is 0, andleft[0] becomesleft[i] only ifi is strictly bigger than the window atwindow[i] .left[i - 1] - Fill the array
in a loop from right to left.right isright[m - 1] , andm - 1 becomesright[i] ifi is at least as big as the window atwindow[i] .right[i + 1] - A last loop moves
frommid whilek is still a start. For eachmid + k , it takesmid anda = left[mid - k] and adds the three window sums intoc = right[mid + k] .total - When
is bigger thantotal , or no answer is stored yet, storebestSum in{a, mid, c} andbest intotal . After the loop, returnbestSum .best
The main3k
import java.util.Arrays;
public class MaximumSumOf3NonOverlappingSubarrays {
public static int[] maxSumOfThreeSubarrays(int[] nums, int k) {
int n = nums.length;
int m = n - k + 1; // number of possible window starts
int[] window = new int[m]; // window[i] = sum of nums[i..i+k-1]
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
if (i >= k) {
sum -= nums[i - k]; // drop the number that left the window
}
if (i >= k - 1) {
window[i - k + 1] = sum;
}
}
int[] left = new int[m]; // left[i]: start of the best window in 0..i
for (int i = 1; i < m; i++) {
left[i] = window[i] > window[left[i - 1]] ? i : left[i - 1]; // tie: keep earlier
}
int[] right = new int[m]; // right[i]: start of the best window in i..m-1
right[m - 1] = m - 1;
for (int i = m - 2; i >= 0; i--) {
right[i] = window[i] >= window[right[i + 1]] ? i : right[i + 1]; // tie: take earlier
}
int[] best = null;
int bestSum = 0;
for (int mid = k; mid + k < m; mid++) { // middle window, with room on both sides
int a = left[mid - k];
int c = right[mid + k];
int total = window[a] + window[mid] + window[c];
if (best == null || total > bestSum) { // tie: keep the earlier answer
best = new int[] {a, mid, c};
bestSum = total;
}
}
return best;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(
maxSumOfThreeSubarrays(new int[] {1, 2, 1, 2, 6, 7, 5, 1}, 2)));
System.out.println(Arrays.toString(
maxSumOfThreeSubarrays(new int[] {1, 2, 1, 2, 1, 2, 1, 2, 1}, 2)));
System.out.println(Arrays.toString(
maxSumOfThreeSubarrays(new int[] {3, 1, 4, 1, 5, 9}, 2)));
System.out.println(Arrays.toString(
maxSumOfThreeSubarrays(new int[] {1, 9, 9, 9, 1}, 1)));
System.out.println(Arrays.toString(
maxSumOfThreeSubarrays(new int[] {9, 3, 8, 7, 9, 6, 6, 6}, 2)));
}
}
Running it prints:
[0, 3, 5]
[0, 2, 4]
[0, 2, 4]
[1, 2, 3]
[0, 2, 4]
The first line, [0, 3, 5][3, 1, 4, 1, 5, 9]k = 2
On the fourth line, [1, 2, 3]k = 1
Look at the last line. The window sums of [9, 3, 8, 7, 9, 6, 6, 6][0, 2, 4]
The >=right>right[0, 2, 7][0, 2, 4]
Complexity
The work is four loops in a row, one each for windowleftright
- Time: O(n), because each of the four loops runs at most n times, once per number or window start, and does a fixed amount of work per step, whatever
is.k - Space: O(n).
,window andleft each holdright entries, and the answer is only three indexes.m = n - k + 1