Maximum Erasure Value — LeetCode 1695 Python Solution
MediumArrayHash TableSliding Window
- Problem
- #1695
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Example
- Input
- nums = [4,2,4,5,6]
- Output
- 17
- Explanation
- The optimal subarray here is [2,4,5,6].
Python solution
Python
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
d = [0] * (max(nums) + 1)
s = list(accumulate(nums, initial=0))
ans = j = 0
for i, v in enumerate(nums, 1):
j = max(j, d[v])
ans = max(ans, s[i] - s[j])
d[v] = i
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array \text{nums} auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1695. Maximum Erasure Value is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1695. Maximum Erasure Value?
- LeetCode 1695. Maximum Erasure Value is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1695. Maximum Erasure Value?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1695. Maximum Erasure Value?
- The Python solution on this page uses O(n), where n is the length of the array \text{nums} auxiliary space.
- What topics does LeetCode 1695. Maximum Erasure Value cover?
- LeetCode 1695. Maximum Erasure Value is tagged Array, Hash Table and Sliding Window on LeetCode.