Maximum Erasure Value
The key idea
To maximize the sum of a subarray with all distinct elements, use a sliding window that shrinks the left boundary whenever a duplicate is encountered, tracking seen indices in a hash map.
Problem
You are given an array of positive integers nums. You may erase a subarray (a contiguous segment) containing unique elements — meaning no two elements in the subarray are equal. Return the maximum possible sum you can obtain by erasing exactly one such subarray.
A subarray is defined as any contiguous sequence of the array.
Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^4
Examples
Input: nums = [4,2,4,5,6]
Output: 17
Input: nums = [5,2,1,2,5,2,1,2,5]
Output: 8
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Sliding Window problems
- Find All Anagrams in a StringMEDIUM
- Longest Continuous Increasing SubsequenceEASY
- Longest Repeating Character ReplacementMEDIUM
- Longest Subarray of 1's After Deleting One ElementMEDIUM
- Longest Substring Without Repeating CharactersMEDIUM
- Max Consecutive Ones IIIMEDIUM
- Maximum Average Subarray IEASY
- Maximum Number of Vowels in a Substring of Given LengthMEDIUM
- Minimum Size Subarray SumMEDIUM
- Minimum Window SubstringHARD
- Permutation in StringMEDIUM
- Sliding Window MaximumHARD