Skip to content

Commit e38fff1

Browse files
committed
LeetCode 1695. Maximum Erasure Value
1 parent 2142bb6 commit e38fff1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Proposed solutions to some LeetCode problems. The first column links to the prob
2626
| [1461. Check If a String Contains All Binary Codes of Size K][lc1461] | Medium | [python](leetcode/has_all_codes.py) |
2727
| [1480. Running Sum of 1d Array][lc1480] | Easy | [python](leetcode/running_sum.py) |
2828
| [1658. Minimum Operations to Reduce X to Zero][lc1658] | Medium | [python](leetcode/minimum-operations-to-reduce-x-to-zero.py) |
29+
| [1695. Maximum Erasure Value][lc1695] | Medium | [python](leetcode/maximum-erasure-value.py) |
2930

3031
[lc1]: https://leetcode.com/problems/two-sum/
3132
[lc3]: https://leetcode.com/problems/longest-substring-without-repeating-characters/
@@ -44,3 +45,4 @@ Proposed solutions to some LeetCode problems. The first column links to the prob
4445
[lc1461]: https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/
4546
[lc1480]: https://leetcode.com/problems/running-sum-of-1d-array/
4647
[lc1658]: https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/
48+
[lc1695]: https://leetcode.com/problems/maximum-erasure-value/

leetcode/maximum-erasure-value.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# https://leetcode.com/problems/maximum-erasure-value/
2+
from typing import List
3+
4+
5+
class Solution:
6+
def maximumUniqueSubarray(self, nums: List[int]) -> int:
7+
seen = {}
8+
sum = 0
9+
left = 0
10+
max_sum = 0
11+
for right in range(len(nums)):
12+
if nums[right] in seen:
13+
# Move the left pointer to the left of the last seen position removing the values from the sum
14+
while left <= seen[nums[right]]:
15+
sum -= nums[left]
16+
left += 1
17+
18+
# Always add the new, or updated, seen position and the value to the sum
19+
seen[nums[right]] = right
20+
sum += nums[right]
21+
max_sum = max(max_sum, sum)
22+
23+
return max_sum
24+
25+
26+
tests = [
27+
[[4, 2, 4, 5, 6], 17],
28+
[[5, 2, 1, 2, 5, 2, 1, 2, 5], 8],
29+
[[1], 1],
30+
[[10000, 1, 10000, 1, 1, 1, 1, 1, 1], 10001]
31+
]
32+
33+
34+
def test():
35+
sol = Solution()
36+
for t in tests:
37+
result = sol.maximumUniqueSubarray(t[0])
38+
assert result == t[1], f'{result} != {t[1]}'
39+
40+
41+
test()

0 commit comments

Comments
 (0)