Skip to content

1695. Maximum Erasure Value 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int maximumUniqueSubarray(vector<int>& nums) {
    int ans = 0;
    int score = 0;
    unordered_set<int> seen;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      while (!seen.insert(nums[r]).second) {
        score -= nums[l];
        seen.erase(nums[l++]);
      }
      score += nums[r];
      ans = max(ans, score);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int maximumUniqueSubarray(int[] nums) {
    int ans = 0;
    int score = 0;
    Set<Integer> seen = new HashSet<>();

    for (int l = 0, r = 0; r < nums.length; ++r) {
      while (!seen.add(nums[r])) {
        score -= nums[l];
        seen.remove(nums[l++]);
      }
      score += nums[r];
      ans = Math.max(ans, score);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def maximumUniqueSubarray(self, nums: list[int]) -> int:
    ans = 0
    score = 0
    seen = set()

    l = 0
    for r, num in enumerate(nums):
      while num in seen:
        score -= nums[l]
        seen.remove(nums[l])
        l += 1
      seen.add(nums[r])
      score += nums[r]
      ans = max(ans, score)

    return ans