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:
- Step 1: Delete any elements from
numsto remove duplicates strategically - 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code