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
Maximum Unique Subarray Sum After Deletion INPUT nums = [4, 2, 4, 5, 6] 4 i=0 2 i=1 4 i=2 5 i=3 6 i=4 Duplicate '4' at index 2 Hash Set Tracking seen = {} Track unique elements in current window Goal: Find max sum subarray with all unique elements ALGORITHM STEPS 1 Initialize Hash Set seen={}, left=0, maxSum=0 2 Sliding Window Expand right pointer 3 Handle Duplicates Shrink window from left 4 Update Max Sum Track best unique subarray Window Processing: [4] sum=4, max=4 [4,2] sum=6, max=6 [4,2,4] dup! shrink [2,4,5] sum=11, max=11 [2,4,5,6] sum=17, max=17 OK - All unique! FINAL RESULT Optimal Subarray Found: 2 4 5 6 2 + 4 + 5 + 6 = 17 OUTPUT 17 Verification: All elements unique: OK Contiguous subarray: OK Maximum sum achieved! Key Insight: Use a Hash Set with sliding window technique to efficiently track unique elements. When a duplicate is found, shrink the window from the left until the duplicate is removed. This gives O(n) time complexity. The hash set enables O(1) lookup for duplicates and maintains the current window state. TutorialsPoint - Maximum Unique Subarray Sum After Deletion | Hash Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
32.0K Views
Medium Frequency
~25 min Avg. Time
850 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