AAlgoLoopSpaced repetition for LeetCode
MEDIUMSliding WindowLeetCode ↗

Maximum Erasure Value

The key idea

To maximize the sum of a subarray with all distinct elements, use a sliding window that shrinks the left boundary whenever a duplicate is encountered, tracking seen indices in a hash map.

Problem

You are given an array of positive integers nums. You may erase a subarray (a contiguous segment) containing unique elements — meaning no two elements in the subarray are equal. Return the maximum possible sum you can obtain by erasing exactly one such subarray.

A subarray is defined as any contiguous sequence of the array.

Constraints

Examples

Input: nums = [4,2,4,5,6] Output: 17
Input: nums = [5,2,1,2,5,2,1,2,5] Output: 8

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Sliding Window problems