Maximum Erasure Value (LeetCode 1695): Solution and Explanation

Medium
Array
Hash table
Sliding window

Given an array of positive integers, find the subarray with all distinct values that has the largest sum. That sum is the best score you can get by erasing one subarray of unique elements.

Intuition

Erasing a subarray scores its sum, and the subarray must not contain a value twice. So the question is: which window of distinct values has the largest sum?

All values are positive, so making a valid window longer never lowers its sum. That means for each right end we want the longest valid window, which is the classic longest-substring-without-repeats setup.

Grow the window to the right. When the new value is already inside, the window cannot keep both copies, so the left edge must move past the earlier copy. Values that leave the window never need to come back, because any window that contains them and the new value is invalid.

Approach: Sliding window with a set and a running sum

  1. Keep seen (values in the window), left = 0, cur = 0 (window sum) and best = 0.
  2. For each value x from left to right: while x is in seen, remove nums[left] from seen, subtract it from cur, and increment left.
  3. Add x to seen and to cur.
  4. Set best = max(best, cur).
  5. Return best.

Step-by-step example

nums = [4,2,4,5,6]
  1. Read 4: the window is [4], cur = 4, best = 4.
  2. Read 2: the window is [4,2], cur = 6, best = 6.
  3. Read 4: 4 is already inside. Drop the first 4 from the left, cur = 2. Now add the new 4: the window is [2,4], cur = 6, best stays 6.
  4. Read 5: the window is [2,4,5], cur = 11, best = 11.
  5. Read 6: the window is [2,4,5,6], cur = 17, best = 17. The answer is 17.

Code: Python, Java, C++

1class Solution:
2    def maximumUniqueSubarray(self, nums: List[int]) -> int:
3        seen = set()
4        left = 0
5        cur = 0
6        best = 0
7        for x in nums:
8            while x in seen:
9                seen.remove(nums[left])
10                cur -= nums[left]
11                left += 1
12            seen.add(x)
13            cur += x
14            best = max(best, cur)
15        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index enters the window once and leaves at most once, and each set operation is O(1) on average.

Space

O(n)

The set holds at most the distinct values of the current window. With nums[i] <= 10^4 a fixed-size boolean array also works.

Other approaches

Last index plus prefix sums (time O(n), space O(n))

Store the last index of each value and prefix sums. When x was last seen at j, jump left to max(left, j + 1) directly and read the window sum as prefix[right + 1] - prefix[left].

Check every start (time O(n^2), space O(n))

For each start index, extend to the right until a repeat appears and keep the largest sum. Simple, but quadratic and too slow for 10^5 elements.

Common mistakes

  • Removing only the duplicate value from the set instead of every value to the left of it. The window must stay contiguous.
  • Using if instead of while for the shrink step, so the left edge stops before the earlier copy is gone.
  • With the last-index trick, forgetting max(left, j + 1): an old index left of the window must not move left backwards.
  • Updating best before adding the new value, which misses windows that end at the current index.

Frequently asked questions

Why does shrinking from the left never lose the answer?

Any window that still contains the earlier copy of x and also contains the new x is invalid. So every start at or before that copy is useless for this right end and all later ones.

Does this rely on the numbers being positive?

Yes. Because every value is positive, the longest valid window ending at each index is also the one with the largest sum. With negative values a shorter window could score more.

What is the time and space complexity?

O(n) time, since each element is added once and removed at most once, and O(n) space for the set of values in the window.

How is this related to Longest Substring Without Repeating Characters?

It is the same window. That problem scores a window by its length; this one scores it by its sum.