Maximum Erasure Value (LeetCode 1695): Solution and Explanation
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
- Keep
seen(values in the window),left = 0,cur = 0(window sum) andbest = 0. - For each value
xfrom left to right: whilexis inseen, removenums[left]fromseen, subtract it fromcur, and incrementleft. - Add
xtoseenand tocur. - Set
best = max(best, cur). - Return
best.
Step-by-step example
nums = [4,2,4,5,6]
- Read 4: the window is [4], cur = 4, best = 4.
- Read 2: the window is [4,2], cur = 6, best = 6.
- 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.
- Read 5: the window is [2,4,5], cur = 11, best = 11.
- 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 best1class Solution {
2 public int maximumUniqueSubarray(int[] nums) {
3 Set<Integer> seen = new HashSet<>();
4 int left = 0, cur = 0, best = 0;
5 for (int right = 0; right < nums.length; right++) {
6 int x = nums[right];
7 while (seen.contains(x)) {
8 seen.remove(nums[left]);
9 cur -= nums[left];
10 left++;
11 }
12 seen.add(x);
13 cur += x;
14 best = Math.max(best, cur);
15 }
16 return best;
17 }
18}1class Solution {
2public:
3 int maximumUniqueSubarray(vector<int>& nums) {
4 unordered_set<int> seen;
5 int left = 0, cur = 0, best = 0;
6 for (int right = 0; right < (int)nums.size(); right++) {
7 int x = nums[right];
8 while (seen.count(x)) {
9 seen.erase(nums[left]);
10 cur -= nums[left];
11 left++;
12 }
13 seen.insert(x);
14 cur += x;
15 best = max(best, cur);
16 }
17 return best;
18 }
19};Time and space complexity
O(n)
Each index enters the window once and leaves at most once, and each set operation is O(1) on average.
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
ifinstead ofwhilefor 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 moveleftbackwards. - Updating
bestbefore 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.