Maximum Unique Subarray Sum After Deletion - Problem
You are given an integer array nums. You are allowed to delete any number of elements from nums without making it empty.
After performing the deletions, select a subarray of nums such that:
- All elements in the subarray are unique.
- The sum of the elements in the subarray is maximized.
Return the maximum sum of such a subarray.
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 sum 17. We can delete the first 4 to make all elements unique.
Example 2 — No Deletions Needed
$
Input:
nums = [5,2,1,2,5,2,1,2,5]
›
Output:
8
💡 Note:
The optimal subarray is [5,2,1] with sum 8. All elements are already unique in this subarray.
Example 3 — Single Element
$
Input:
nums = [1]
›
Output:
1
💡 Note:
The array has only one element, so the maximum sum is 1.
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array [4,2,4,5,6] with duplicate 4
2
Find Unique Subarray
Find subarray [2,4,5,6] with all unique elements
3
Calculate Sum
Sum = 2+4+5+6 = 17
Key Takeaway
🎯 Key Insight: Use sliding window with hash set to efficiently find the longest subarray with unique elements that gives maximum sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code