Maximum Erasure Value

Find the largest sum of a run of neighbouring numbers that holds no value twice.

Given an array of positive integers nums, erase one subarray whose elements are all different. A subarray is a run of neighbouring elements, such as [2, 4, 5] inside [4, 2, 4, 5, 6]. Erasing it scores the sum of its elements. Return the largest score possible. Every value in nums is between 1 and 10,000.

Example 1
Input: nums = [4, 2, 4, 5, 6]
Output: 17
Explanation: [2, 4, 5, 6] has no repeats and sums to 17.
Example 2
Input: nums = [5, 2, 1, 2, 5, 2, 1, 2, 5]
Output: 8
Explanation: [5, 2, 1] or [1, 2, 5].
Solution

The Idea

Picture a row of number tiles: 4, 2, 4, 5, 6. You may pick up one unbroken stretch of tiles and score the numbers on them, but the stretch may not hold the same number twice. Picking up 4 and 2 scores 6. Picking up all five tiles is not allowed, because that stretch holds two 4s. The best pick is 2, 4, 5, 6, worth 17.

How can we find that pick without trying every stretch? Start at the left end and grow a stretch one tile at a time, keeping a running sum. Every number is positive, so each tile that joins makes the sum bigger, and a stretch should grow for as long as it can. The only thing that stops it is a number that is already inside.

Two markers keep track of the stretch: right sits on the newest tile in it, and left on the oldest. Now follow the stretch through the example. Look at the picture below, where the stretch is drawn as a box.

The window over 4, 2, 4, 5, 6 in three moments. After 2 joins, the window is 4, 2 with sum 6. When the second 4 joins, the first 4 leaves from the left, so the window is 2, 4 with sum 6. After 6 joins, the window is 2, 4, 5, 6 with sum 17.

In the row labelled "2 has joined", the box holds 4 and 2, and the sum is 6. In the row labelled "the second 4 joins", the new 4 would repeat the first one, so the first 4 leaves from the left. The box now holds 2 and 4, and the sum is still 6. In the row labelled "6 has joined", 5 and 6 are in too, and the sum is 17, the answer.

Why drop tiles from the left, and not start a new stretch at the second 4? A stretch that ends at the second 4 and has no repeats cannot include the first 4, so it starts after it. But it can still include the 2, and starting over would throw that 2 away.

So both markers only ever move forward. right takes the next tile, and left moves only until the repeat is gone. A stretch whose two ends move forward like this is called a sliding window. Longest Substring Without Repeating Characters is the same problem on characters, where the window's length counts instead of its sum.

Solution Approach

Turning that idea into code means settling three things: how to tell whether a value is already in the window, how far left moves when a repeat arrives, and how to keep the sum up to date.

Checking whether a value is in the window

How do we know that a new value is already inside? Scanning the whole window each time would be slow. A set of the values in the window answers in one step. Since every value is between 1 and 10,000, a boolean[10001] array called inWindow can be that set: inWindow[v] is true while the value v is in the window.

The value is its own index, so there is no hashing to do, and the array is faster than Java's general-purpose HashSet. Slot 0 is never used, which is why the array has 10,001 slots and not 10,000.

Moving the left edge

How far must left move? Not always one place. In Example 2 the window holds 5, 2 and 1 when the second 2 arrives. The earlier 2 is in the middle, so 5 has to leave first, then the 2, and the window becomes 1, 2.

So left moves in a loop: clear the slot of the value it is on, subtract that value from the sum, step forward, and check again, until the new value's slot is false. This loop sits inside the loop over right, yet the total work stays small. Each element leaves the window at most once, so for an array of n numbers, left takes at most n steps over the whole run.

Keeping the sum

The simple way is to try every starting position and add numbers until a repeat appears. For an array with no repeats at all, that adds about n²/2 numbers. The window does better by keeping one running sum: add a value when it joins, and subtract it when it leaves. After each new value joins, best keeps the largest sum seen so far.

Can sum grow too big for an int? A window holds each value at most once, so its sum is at most 1 + 2 + ... + 10,000 = 50,005,000. An int holds values up to about 2.1 billion, so it is enough.

Java Solution

The method maximumUniqueSubarray works in these steps:

  1. First, create the inWindow array with 10,001 slots, and set left, sum and best to 0.
  2. A for loop moves right from the first position to the last. nums[right] is the value about to join the window.
  3. Inside, a while loop runs as long as inWindow[nums[right]] is true. Each round clears the slot of nums[left], subtracts nums[left] from sum, and moves left one place right.
  4. Once the repeat is gone, set inWindow[nums[right]] to true, add nums[right] to sum, and keep the larger of best and sum in best.
  5. When the for loop ends, return best.

The main method runs both examples, an array of one value repeated, an array with a single number, and the numbers 1 to 10,000, which have no repeats at all.

Java
public class MaximumErasureValue {

    public static int maximumUniqueSubarray(int[] nums) {
        boolean[] inWindow = new boolean[10001];   // values are between 1 and 10,000
        int left = 0;
        int sum = 0;
        int best = 0;
        for (int right = 0; right < nums.length; right++) {
            while (inWindow[nums[right]]) {   // remove from the left until the copy is gone
                inWindow[nums[left]] = false;
                sum -= nums[left];
                left++;
            }
            inWindow[nums[right]] = true;
            sum += nums[right];
            best = Math.max(best, sum);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maximumUniqueSubarray(new int[] {4, 2, 4, 5, 6}));
        System.out.println(maximumUniqueSubarray(new int[] {5, 2, 1, 2, 5, 2, 1, 2, 5}));
        System.out.println(maximumUniqueSubarray(new int[] {3, 3, 3}));
        System.out.println(maximumUniqueSubarray(new int[] {7}));
        int[] all = new int[10000];
        for (int i = 0; i < all.length; i++) {
            all[i] = i + 1;                   // 1, 2, ..., 10000: no repeats at all
        }
        System.out.println(maximumUniqueSubarray(all));
    }
}

Running it prints:

Output
17
8
3
7
50005000

17 and 8 match the two examples. In [3, 3, 3], each new 3 pushes the old one out of the window, so the window never holds more than one element, and the third line is 3. A single number is a window on its own, so [7] gives 7.

The last line, 50005000, is 1 + 2 + ... + 10,000. Here the window takes in the whole array and left never moves. It is also the largest sum any window can have, and it fits in an int.

Why a while loop and not an if? With an if, only one element leaves for each new value. Example 1 still gives 17 that way, because the repeated 4 is the leftmost element. Example 2 gives 10 instead of 8. When the second 2 arrives, only the 5 leaves, and the window 2, 1, 2 keeps a repeat. The next 5 joins it, and 2, 1, 2, 5 sums to 10.

Complexity

The work is one pass of right over the array, plus the steps of left, which can never outnumber the steps of right.

  • Time: O(n), because right brings each of the n numbers into the window once, and left takes each one out at most once. The while loop therefore runs at most n times in total, across all values of right.
  • Space: O(V), where V = 10,000 is the largest value allowed. inWindow has one slot per possible value, however long the array is, and the rest is sum, best and the two markers.