Taro Logo

Maximum Erasure Value

#1 Most AskedMedium
3 views
Topics:
ArraysTwo PointersSliding Windows

You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.

Return the maximum score you can get by erasing exactly one subarray.

An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).

Example 1:

Input: nums = [4,2,4,5,6]
Output: 17
Explanation: The optimal subarray here is [2,4,5,6].

Example 2:

Input: nums = [5,2,1,2,5,2,1,2,5]
Output: 8
Explanation: The optimal subarray here is [5,2,1] or [1,2,5].

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected behavior and return value if the input array is empty or null?
  2. Are the elements in the input array guaranteed to be strictly positive integers, or could there be zeros and negative numbers?
  3. Can the array contain duplicate values, and if so, does our subarray need to strictly contain all unique elements?
  4. What should be returned if multiple subarrays share the exact same maximum score?
  5. Should I return the maximum score (sum of elements) itself, or the subarray elements / their indices?

Brute Force Solution

Approach

The brute force approach to finding the maximum erasure value involves exploring every single possible continuous segment of numbers. For each possible segment, we check if all the numbers inside it are completely unique before calculating their total sum.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at every possible starting position within the sequence of numbers.
  2. For each starting position, consider every possible ending position that comes on or after it to form a continuous segment.
  3. Examine the numbers contained inside the chosen segment to see if any number appears more than once.
  4. If the segment contains any duplicate numbers, ignore it and move on to the next possibility.
  5. If all the numbers in the segment are unique, calculate the total sum of those numbers.
  6. Keep a running record of the highest sum you have found so far.
  7. Repeat this checking process for every single continuous segment possible.
  8. After exhausting all possibilities, the highest sum you recorded is your final answer.

Code Implementation

def maximum_erasure_value(numbers_list):
    highest_score_found = 0
    
    # Explore every possible continuous segment by iterating over all start and end positions
    for start_position in range(len(numbers_list)):
        for end_position in range(start_position, len(numbers_list)):
            current_segment = numbers_list[start_position:end_position + 1]
            
            # Check if all numbers in the segment are unique to ensure it is a valid erasure
            if len(current_segment) == len(set(current_segment)):
                current_segment_sum = sum(current_segment)
                
                # Update our running record if the current segment sum exceeds all previous sums
                if current_segment_sum > highest_score_found:
                    highest_score_found = current_segment_sum
                    
    return highest_score_found

Big(O) Analysis

Time Complexity
O(n³) – For an array of size n, we use two nested loops to generate every possible starting and ending position, which results in about n * n / 2 possible segments. For each segment, a third step scans through its elements to check for duplicates and calculate the sum, taking up to n additional operations per segment. This combination leads roughly to n cubed over 6 operations, which simplifies to a cubic time complexity of O(n³) due to the nested evaluation of segments and their contents.
Space Complexity
O(n) – To implement the tracking of unique elements and running sums across continuous segments for an input of size N, the algorithm utilizes an auxiliary hash set or frequency map alongside a few primitive tracking variables. In the worst-case scenario where all elements in the sequence are unique, this hash structure stores up to N distinct values simultaneously. Because the extra memory required grows directly in proportion to the number of input elements, the auxiliary space complexity scales linearly with the input size N.

Optimal Solution

Approach

To find the most valuable unique sequence, we can slide a flexible window across our collection of items, gathering them one by one. Whenever we notice we have collected a duplicate item, we simply shrink our window from the starting side until the duplicate is gone, ensuring every item in our current view is completely unique.

Here's how the algorithm would work step-by-step:

  1. Imagine you are looking at a line of items and want to find a stretch where no item repeats, while adding up their values to be as large as possible.
  2. Start at the very beginning of the line and begin gathering items into your current collection, keeping a running total of their values.
  3. As you add each new item, check to see if you have accidentally collected a duplicate of something already in your current collection.
  4. If you find a duplicate, gently release items from the front of your collection one by one, subtracting their values from your total, until the duplicate is completely gone.
  5. Keep track of the highest total score you have achieved during this process.
  6. Continue moving forward, expanding your collection with new items and trimming from the front whenever duplicates appear.
  7. Once you reach the very end of the line, the highest recorded total score will be your final answer.

Code Implementation

class Solution:
    def maximum_unique_subarray(self, nums: list[int]) -> int:
        seen_elements = set()
        start_pointer = 0
        current_window_sum = 0
        maximum_total_score = 0

        for end_pointer in range(len(nums)):
            # We shrink the window from the left until all duplicates are removed to maintain uniqueness.
            while nums[end_pointer] in seen_elements:
                seen_elements.remove(nums[start_pointer])
                current_window_sum -= nums[start_pointer]
                start_pointer += 1

            seen_elements.add(nums[end_pointer])
            current_window_sum += nums[end_pointer]

            # We update the maximum score only when we find a strictly better unique window total.
            if current_window_sum > maximum_total_score:
                maximum_total_score = current_window_sum

        return maximum_total_score

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the number of items in the array. The algorithm uses a sliding window approach driven by a right pointer that iterates through each of the n elements exactly once. When a duplicate is encountered, a left pointer advances forward to shrink the window, but this left pointer only moves in the forward direction and never backtracks. Across the entire execution, each element is visited at most once by the right pointer and at most once by the left pointer. Therefore, the total number of operations scales linearly with the input size n, simplifying to O(n).
Space Complexity
O(n) – The auxiliary space is driven by a hash map used to store the most recent index of each unique item collected within our sliding window. In the worst-case scenario where all elements in the input array of size N are completely unique, this hash map will store N distinct key-value pairs. Additionally, a few primitive integer variables are used to track pointers and running totals, requiring constant O(1) extra space. Therefore, the total extra memory scales directly with the number of unique elements, leading to a space complexity of O(N).

Edge Cases

Empty or null array input
How to Handle:
Return zero immediately because the score of an empty subarray is zero.
Array with a single element
How to Handle:
The sliding window will process the single element and return its value as the maximum score.
Array with all identical elements
How to Handle:
The left pointer will advance past the duplicate, restricting the valid window size to exactly one element.
Array with no duplicate elements
How to Handle:
The sliding window will expand to encompass the entire array and return the sum of all elements.
Array with tightly clustered duplicates at the very end
How to Handle:
The window correctly shrinks from the left to expel the duplicate while maintaining the peak running sum.
Maximum possible array size with large integer values
How to Handle:
Using a linear time sliding window approach with a hash set and 64-bit integers prevents overflow and time-out issues.
Intermittent duplicate values scattered throughout the array
How to Handle:
A frequency map or set tracks element indices to dynamically contract the window start whenever a repeat is encountered.
Maximum constraint values where the sum exceeds standard 32-bit integer limits
How to Handle:
Using 64-bit integer types for sum accumulation ensures the result does not overflow during computation.
0/8 completed