Maximum Erasure Value - Problem

You have an array of positive integers and need to find the most valuable subarray you can "erase" - but there's a catch! The subarray must contain only unique elements (no duplicates).

Your score is the sum of all elements in the erased subarray. Your goal is to find the maximum possible score by choosing the optimal contiguous subarray.

Example: Given [4,2,4,5,6], you could erase [4,2] (score = 6), [2,4,5,6] (score = 17), or [4,5,6] (score = 15). The maximum score is 17.

Think of it as a sliding window problem where you want to find the longest valid window with the highest sum!

Input & Output

example_1.py โ€” Python
$ Input: [4,2,4,5,6]
โ€บ Output: 17
๐Ÿ’ก Note: The optimal subarray is [2,4,5,6] with sum 2+4+5+6=17. We can't include the first 4 because then we'd have duplicate 4s.
example_2.py โ€” Python
$ Input: [5,2,1,2,5,2,1,2,5]
โ€บ Output: 8
๐Ÿ’ก Note: The optimal subarray is [5,2,1] with sum 5+2+1=8. Any longer subarray would contain duplicates.
example_3.py โ€” Python
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: With only one element, that element forms the only possible subarray with sum 1.

Visualization

Tap to expand
Sliding Window42456371โ†‘ leftโ†‘ rightCurrent Sum: 2+4+5+6 = 17Algorithm Steps:1. Found duplicate 4 at current position2. Move left pointer past first occurrence of 43. Current window: [2,4,5,6] with sum 174. This is our maximum so far!โœ“ Optimal subarray found
Understanding the Visualization
1
Expand Window
Move right pointer to include new elements in the window
2
Check Duplicates
Use hash map to detect if current element creates a duplicate in window
3
Shrink Window
When duplicate found, move left pointer past the previous occurrence
4
Track Maximum
Continuously update the maximum sum across all valid windows
Key Takeaway
๐ŸŽฏ Key Insight: Instead of restarting from scratch when we find duplicates, we can efficiently slide our window by moving the left boundary past the duplicate element, achieving linear time complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each element is visited at most twice (once by right pointer, once by left pointer)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map to store element positions, worst case stores all elements

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 104
  • All elements are positive integers
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
125.0K Views
High Frequency
~18 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen