Maximum Erasure Value - Problem

You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.

Return the maximum score you can get by erasing exactly one subarray.

A subarray b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l], a[l+1], ..., a[r] for some (l, r).

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,4,5,6]
Output: 17
💡 Note: The optimal subarray is [2,4,5,6] with all unique elements and sum = 2+4+5+6 = 17
Example 2 — Single Element
$ Input: nums = [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
Example 3 — All Unique
$ Input: nums = [1,2,3,4]
Output: 10
💡 Note: All elements are unique, so we take the entire array: 1+2+3+4 = 10

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Erasure Value INPUT Array nums: 4 i=0 2 i=1 4 i=2 5 i=3 6 i=4 Goal: Find contiguous subarray with unique elements having maximum sum Hash Set for Tracking: {seen elements} Use sliding window with two pointers left=0, right=0 ALGORITHM STEPS 1 Initialize left=0, sum=0, maxSum=0 hashSet = empty 2 Expand Window For each right index: If nums[right] not in set Add to set, add to sum 3 Shrink if Duplicate While duplicate found: Remove nums[left] from set Subtract from sum, left++ 4 Update Maximum maxSum = max(maxSum, sum) Continue until end Trace Example: [4,2,4,5,6] sum=6, dup 4! [2,4,5,6] sum=17 (best!) Window: i=1 to i=4 Set: {2,4,5,6} FINAL RESULT Best Subarray Found: 4 2 4 5 6 Selected: [2,4,5,6] Calculation: 2 + 4 + 5 + 6 = 17 Output: 17 Verification: OK All elements unique Maximum possible sum Key Insight: The Hash Set allows O(1) lookup to detect duplicates. When a duplicate is found, shrink the window from the left until the duplicate is removed. This sliding window approach achieves O(n) time complexity since each element is added and removed at most once from the set. TutorialsPoint - Maximum Erasure Value | Hash Set + Sliding Window Approach Time: O(n) | Space: O(n)
Asked in
Amazon 25 Microsoft 18 Google 12
28.0K Views
Medium Frequency
~15 min Avg. Time
892 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