Maximum Unique Subarray Sum After Deletion - Problem

You're given an integer array nums and have the power to delete any elements you want (but not all of them). Your goal is to find a contiguous subarray with all unique elements that has the maximum possible sum.

Think of it as a two-step optimization problem:

  1. Step 1: Delete any elements from nums to remove duplicates strategically
  2. Step 2: Find the contiguous subarray with maximum sum from the remaining elements

The key insight is that you want to keep the largest occurrence of each duplicate element and delete the smaller ones, then find the maximum subarray sum.

Example: If nums = [4,2,4,5,6], you can delete the first 4 to get [2,4,5,6], then the entire array forms a unique subarray with sum 17.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [4,2,4,5,6]
โ€บ Output: 17
๐Ÿ’ก Note: The optimal subarray is [2,4,5,6] with sum 17. We delete the first 4 to avoid duplicates, then take the remaining contiguous elements.
example_2.py โ€” All Unique
$ Input: nums = [5,2,1,2,5,2,1,2,5]
โ€บ Output: 8
๐Ÿ’ก Note: The optimal subarray is [5,2,1] with sum 8. Even though we have many duplicates, the best unique subarray has sum 8.
example_3.py โ€” Single Element
$ Input: nums = [1]
โ€บ Output: 1
๐Ÿ’ก Note: With only one element, the maximum unique subarray sum is just that element itself.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 104
  • The array will not be empty after deletions

Visualization

Tap to expand
๐ŸŽฏ Sliding Window Treasure Collection๐Ÿ’Ž4๐Ÿ’ 2๐Ÿ’Ž4๐Ÿ”ธ5๐Ÿ”ถ6Current Collection WindowStartEndAlgorithm Steps1. Expand: Add treasures to collection while all are unique2. Contract: When duplicate found (๐Ÿ’Ž4), skip past previous ๐Ÿ’Ž43. Update: Current collection [๐Ÿ’ 2, ๐Ÿ’Ž4, ๐Ÿ”ธ5, ๐Ÿ”ถ6] = 17 pointsโœ“ Result: Maximum collection value = 17Time: O(n) | Space: O(min(unique_elements, n))
Understanding the Visualization
1
Start Collection
Begin collecting treasures from the left, keeping track of what you've seen
2
Handle Duplicates
When you encounter a duplicate, abandon treasures up to and including the previous occurrence
3
Track Maximum
Always remember the highest value collection you've achieved
4
Continue Optimally
Keep extending your collection to the right while maintaining uniqueness
Key Takeaway
๐ŸŽฏ Key Insight: Instead of trying all possible deletions, we use a sliding window that automatically handles duplicates by moving the start pointer past the previous occurrence. This gives us the optimal solution in linear time!
Asked in
Google 45 Amazon 35 Microsoft 28 Meta 22
42.0K Views
High Frequency
~18 min Avg. Time
1.6K 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