Magicsheet logo

Maximum Erasure Value

Medium
100%
Updated 6/1/2025

Maximum Erasure Value

1. What is this problem about?

Maximum Erasure Value asks you to find the maximum sum of a subarray that contains only unique elements. You are given an array of positive integers and you want to 'erase' a contiguous sequence of unique numbers to get the highest score.

2. Why is this asked in interviews?

This is a quintessential Sliding Window interview question asked by Microsoft, Meta, and Google. It tests whether a candidate can efficiently manage a dynamic range of elements. It also evaluates knowledge of Hash Sets for uniqueness checks and the ability to maintain a running sum, which is more efficient than re-calculating the sum for every window.

3. Algorithmic pattern used

The problem is solved using the Sliding Window pattern with a Hash Set. You maintain two pointers, left and right. You expand the window by moving right and adding the element to the sum and the set. If you encounter a duplicate, you shrink the window from the left (subtracting from sum and removing from set) until the duplicate is gone. Throughout the process, you keep track of the maximum sum observed.

4. Example explanation

Array: [4, 2, 4, 5, 6]

  • Right at 0 (4): Sum=4, Max=4, Set={4}
  • Right at 1 (2): Sum=6, Max=6, Set={4, 2}
  • Right at 2 (4): Duplicate!
    • Move Left: Remove 4. Sum=2, Set={2}
    • Now add 4: Sum=6, Max=6, Set={2, 4}
  • Right at 3 (5): Sum=11, Max=11, Set={2, 4, 5}
  • Right at 4 (6): Sum=17, Max=17, Set={2, 4, 5, 6} Result: 17.

5. Common mistakes candidates make

A common error is not using a Hash Set to track uniqueness, which can lead to O(n²) if you search the window manually. Another mistake is forgetting to subtract the removed element from the running sum when shrinking the window. Some also struggle with the boundary conditions of the while loop used for shrinking the window.

6. Interview preparation tip

Sliding Window is one of the most common patterns for array/string problems. Whenever you hear 'contiguous subarray' and a 'uniqueness' or 'constraint' condition, your mind should immediately go to the two-pointer sliding window technique.

Similar Questions