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 nums and a length k. Choose three subarrays of length k, that is, three runs of k numbers that sit next to each other, so that no number belongs to two of them. Make the sum of all their numbers as large as possible, and return the starting index of each subarray, smallest first. The array has at least 3k numbers.

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

The Idea

Think of nums as the number of visitors a shop gets each day. You may run three promotions of k days each, never two at the same time, and you want them on the days that bring the most visitors in total.

A run of k numbers is like a frame of k cells that you can slide along the array, so from here on we call it a window, and the sum of its numbers its window sum. In Example 1, with k = 2, a window can start at index 0 to 6, and the window sums of those seven windows are 3, 3, 3, 8, 13, 12 and 6.

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.

nums = 1, 2, 1, 2, 6, 7, 5, 1 with k = 2. The window sums by start are 3, 3, 3, 8, 13, 12, 6. With the middle window at start 3, the left window can start at 0 or 1 and the best is 0, the right window can start at 5 or 6 and the best is 5. Total 3 + 8 + 12 = 23.

The top row is nums, and the row below it, labelled "window sum by start", holds each window sum under the index where its window starts. The middle window starts at 3 and covers 2 and 6, so its window sum is 8. The left window must end by index 2, so it starts at 0 or 1. Both sums are 3, and we take the earlier start, 0, as the tie rule asks. The right window must start at 5 or later: 12 at start 5 beats 6 at start 6. That gives 3 + 8 + 12 = 23, the answer [0, 3, 5].

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 numbers for every window repeats a lot of work, because neighboring windows share all but one number at each end. Instead, keep a running sum and slide it one step at a time.

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 is.

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 mid take? There must be room for a whole window on each side. The left window needs indexes 0 to k - 1, so mid starts at k. The right window must start at mid + k or later, and that start must still exist. In Example 1, mid runs from 2 to 4.

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] is the start of the largest window among starts 0 to i. It is either i itself or the best one before it, left[i - 1], so one pass from left to right fills it.

right[i] is the start of the largest window among starts i to the last one, filled by one pass from right to left. For a middle window at mid, the left window is left[mid - k] and the right window is right[mid + k]. In the picture, those are left[1] = 0 and right[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 is filled from the left, so it moves to a new start only when that window is strictly bigger.

right is filled from the right, so an equal window it meets later in its pass is further left in the array. So on an equal sum it moves to the new start too. Finally, mid goes from left to right, and the best answer is replaced only by a strictly larger total.

Java Solution

The method maxSumOfThreeSubarrays works in these steps:

  1. First, set n to the length of nums and m = n - k + 1, the number of possible window starts, and fill the array window in one loop over nums. A running total, sum, adds nums[i], drops nums[i - k] once the window is full, and is stored in window[i - k + 1].
  2. Fill the array left in a loop from left to right. left[0] is 0, and left[i] becomes i only if window[i] is strictly bigger than the window at left[i - 1].
  3. Fill the array right in a loop from right to left. right[m - 1] is m - 1, and right[i] becomes i if window[i] is at least as big as the window at right[i + 1].
  4. A last loop moves mid from k while mid + k is still a start. For each mid, it takes a = left[mid - k] and c = right[mid + k] and adds the three window sums into total.
  5. When total is bigger than bestSum, or no answer is stored yet, store {a, mid, c} in best and total in bestSum. After the loop, return best.

The main method runs both examples, an array of exactly 3k numbers, an array where the three windows touch, and an array whose biggest window is not part of the answer.

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

Output
[0, 3, 5]
[0, 2, 4]
[0, 2, 4]
[1, 2, 3]
[0, 2, 4]

The first line, [0, 3, 5], is the choice from the picture. In Example 2, on the second line, every window sums to 3, so every set of three ties at 9, and the earliest starts win. The third line comes from [3, 1, 4, 1, 5, 9]: six numbers and k = 2 leave only one way to place three windows.

On the fourth line, [1, 2, 3] picks the three 9s with k = 1. The windows sit right next to each other, which is allowed, because no number belongs to two of them.

Look at the last line. The window sums of [9, 3, 8, 7, 9, 6, 6, 6] are 12, 11, 15, 16, 15, 12 and 12. Taking the 16 at start 3 leaves 12 on each side, 40 in all. The answer [0, 2, 4] skips the 16 and gets 12 + 15 + 15 = 42.

The >= in the loop that fills right matters. With > there instead, right keeps the later of two equal windows, and Example 2 prints [0, 2, 7]. Its total is also 9, but [0, 2, 4] comes first.

Complexity

The work is four loops in a row, one each for window, left, right and the middle window.

  • 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 k is.
  • Space: O(n). window, left and right each hold m = n - k + 1 entries, and the answer is only three indexes.

Trapping Rain Water also works by knowing, for every position, the best value to its left and the best value to its right.