#1695
Maximum Erasure Value
MediumArrayHash TableSliding WindowHash MapArraySliding Window
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)
The optimal solution uses the sliding window technique to efficiently find the maximum score of a subarray with unique elements. This reduces the need to check every possible subarray explicitly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers (left and right) and a set to track unique elements.
- 2Step 2: Expand the right pointer to include elements in the window until a duplicate is found.
- 3Step 3: If a duplicate is found, move the left pointer to shrink the window until all elements are unique again.
- 4Step 4: Keep track of the current sum and update the maximum score whenever the window is valid.
solution.py14 lines
1# Full working Python code
2
3def maximumErasureValue(nums):
4 left, max_score, current_sum = 0, 0, 0
5 unique_elements = set()
6 for right in range(len(nums)):
7 while nums[right] in unique_elements:
8 unique_elements.remove(nums[left])
9 current_sum -= nums[left]
10 left += 1
11 unique_elements.add(nums[right])
12 current_sum += nums[right]
13 max_score = max(max_score, current_sum)
14 return max_scoreℹ
Complexity note: The time complexity is O(n) because each element is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(n) due to the set storing unique elements.
- 1Using a sliding window allows us to efficiently manage the uniqueness of elements in the current subarray.
- 2Tracking the sum dynamically as we expand and contract the window helps avoid recalculating sums repeatedly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.