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: Find Max Sum Unique Subarray42456Input: [4,2,4,5,6]Sum: 4Sum: 6Optimal: [2,4,5,6] Sum: 17Sum: 4Sum: 11Sum: 6Maximum Erasure Value: 17
Understanding the Visualization
1
Input Array
Array with possible duplicates: [4,2,4,5,6]
2
Find Unique Subarrays
Identify all contiguous subarrays with unique elements
3
Maximum Sum
Return sum of optimal subarray: 17
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find the longest unique subarray with maximum sum
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