#3487
Maximum Unique Subarray Sum After Deletion
EasyArrayHash TableGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a sliding window approach with a hash set to track unique elements. Expand the window to include new elements and shrink it when duplicates are found, maximizing the sum.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a set to track unique elements and two pointers for the sliding window.
- 2Step 2: Iterate through the array, adding elements to the set and updating the current sum.
- 3Step 3: If a duplicate is found, move the left pointer to remove elements until the subarray is unique again.
solution.py14 lines
1def maxUniqueSubarray(nums):
2 seen = set()
3 left = 0
4 max_sum = 0
5 current_sum = 0
6 for right in range(len(nums)):
7 while nums[right] in seen:
8 seen.remove(nums[left])
9 current_sum -= nums[left]
10 left += 1
11 seen.add(nums[right])
12 current_sum += nums[right]
13 max_sum = max(max_sum, current_sum)
14 return max_sumℹ
Complexity note: The sliding window approach processes each element once, leading to O(n) complexity.
- 1Using a set helps efficiently track unique elements.
- 2Sliding window optimizes the search for unique subarrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.