640/670

640. Maximum Erasure Value

Medium

You are given an array of positive integers nums. You get to erase exactly one subarray (a contiguous run of elements), but only if every value inside it is distinct — no repeats allowed. Your score is the sum of what you erase.

Return the highest score you can achieve, i.e. the maximum sum over all duplicate-free subarrays of nums.

Example 1:

Input: nums = [4, 2, 4, 5, 6]

Output: 17

Explanation: The run [2, 4, 5, 6] has no repeats and sums to 17. Including the first 4 would put two 4s in the same run, which is not allowed.

Example 2:

Input: nums = [5, 2, 1, 2, 5, 2, 1, 2, 5]

Output: 8

Explanation: No duplicate-free run can be longer than 3 here. The best are [5, 2, 1] and [1, 2, 5], each summing to 8.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴

Hints:

"Best contiguous run with all-distinct elements" is the shape of Longest Substring Without Repeating Characters — except you maximize a sum instead of a length.

Slide a window: a hash set tells you in O(1) whether the incoming element already lives in the window.

When the new element is a duplicate, evict from the left until its old copy leaves. Keep a running window sum so both add and evict are O(1).

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [4, 2, 4, 5, 6]

Expected output: 17