1695. Maximum Erasure Value
https://leetcode.com/problems/maximum-erasure-value/
Python
Two Pointers with Hashmap
(Catepillar Two Pointer, Same Direction Two Pointer)
- Time: O()
- Space: O()
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
seen = set()
score, max_score = 0, 0
start = 0
for end in range(len(nums)):
while nums[end] in seen:
seen.remove(nums[start])
score -= nums[start]
start += 1
score += nums[end]
seen.add(nums[end])
max_score = max(max_score, score)
return max_score
Javascript
var maximumUniqueSubarray = function(nums) {
let slow = 0;
let fast = 0;
const hashmap = new Map();
let max = -1;
let sum = 0;
while (fast < nums.length) {
sum += nums[fast];
if (hashmap.has(nums[fast])) {
max = Math.max(max, sum - nums[fast]);
while (slow <= hashmap.get(nums[fast])) {
sum -= nums[slow];
slow++;
}
hashmap.delete(nums[fast]);
}
hashmap.set(nums[fast], fast);
fast++;
}
max = Math.max(max, sum);
return max;
};