Maximum Erasure Value

Updated on 10 June, 2025

Problem Statement

You are tasked with identifying a contiguous subarray from a given array of positive integers, where all elements are unique. The objective is to find such a subarray such that if you were to 'erase' this part of the array, the sum of its values would be maximized. The score of erasing a subarray is computed by summing up all its elements. Your goal is to compute the maximum score possible by erasing exactly one subarray which must consist exclusively of unique elements.

Examples

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

Approach and Intuition

Given the nature of the problem, with its focus on maximizing a sum of unique-element subarrays, a logical approach involves the use of a sliding window technique combined with tracking mechanisms for elements to ensure uniqueness. Here's a step-by-step breakdown of the proposed method:

  1. Initialize two pointers to define the window - commonly left and right pointers.
  2. Use a hash map or set to keep track of the elements in the current window and ensure all elements are unique.
  3. Expand the right pointer to extend the window until a duplicate element is encountered or the end of the array is reached.
  4. As you expand the window, keep updating the current sum of the window.
  5. When a duplicate is encountered, move the left pointer to shrink the window until the duplicate is excluded, ensuring the uniqueness of elements within the window.
  6. Continuously update and track the maximum sum encountered.
  7. Continue this process until the right pointer has traversed the entire array.

This technique leverages the efficiency of the sliding window to check each element once, adjusting the window boundaries as duplicates are encountered and removed. By doing this, we ensure that the time complexity is efficient, ideally near linear relative to the size of the input array.

The intuition behind using a sliding window here is due to the need for exploring subarrays of variable sizes to find the maximum sum possible. Tracking the largest sum during this traversal allows for efficient determination of the optimal score in a single pass of the array, minimizing unnecessary recalculations.

Solutions

  • C++
  • Java
cpp
class Solution {
public:
    int maxUniqueSubarraySum(vector<int>& nums) {
        int length = nums.size(), maxSum = 0, low = 0, maxVal = 10001;
        vector<int> indexes(maxVal, -1);
        vector<int> cumulativeSum(length + 1, 0);
        for (int high = 0; high < length; high++) {
            int val = nums[high];
            cumulativeSum[high + 1] = cumulativeSum[high] + val;
            if (indexes[val] >= 0) {
                low = max(low, indexes[val] + 1);
            }
            maxSum = max(maxSum, cumulativeSum[high + 1] - cumulativeSum[low]);
            indexes[val] = high;
        }
        return maxSum;
    }
};

In this solution, the goal is to find the maximum sum of any contiguous subarray in a given list of integers, where all integers are unique within the subarray. The approach utilizes a sliding window technique combined with a hashmap to keep track of the most recent indices of each number within the array.

Follow these steps to understand the method implemented in the C++ code:

  1. Initialize variables for the size of the array (length), maximum sum identified (maxSum), the starting point of the sliding window (low), and establish a limit (maxVal) to create a sufficiently large vector to keep track of indices.
  2. Create two vectors: indexes initialized with -1 to keep track of the latest index of each number, and cumulativeSum to store the running sum of elements up to current index for easy calculation of sum within a range.
  3. Iterate through the array using an index (high) that represents the end of the current window:
    • Update cumulativeSum for current index by adding the value at nums[high].
    • If the current number was seen before (i.e., indexes[nums[high]] is not -1), update low to ensure no numbers are repeated in the current subarray.
    • Calculate the sum of the current subarray by subtracting the cumulative sum at the start of the window (low) from that at the end (high + 1). Update maxSum if this new sum is greater.
    • Update the last seen index of current number in indexes.
  4. Return maxSum as the result which holds the maximum sum of a unique-element subarray.

With this efficient approach, each element in the array is processed in constant time, leading to a solution that scales linearly with the size of the input array.

java
class Solution {
    public int maxUniqueSubarray(int[] elements) {
        int len = elements.length, maxVal = 10001;
        int[] lastIndex = new int[maxVal];
        int[] accumSum = new int[len + 1];
        Arrays.fill(lastIndex, -1);
        int maxSum = 0, windowStart = 0;
        for (int windowEnd = 0; windowEnd < len; windowEnd++) {
            int element = elements[windowEnd];
            accumSum[windowEnd + 1] = accumSum[windowEnd] + element;
            if (lastIndex[element] != -1) {
                windowStart = Math.max(windowStart, lastIndex[element] + 1);
            }
            maxSum = Math.max(maxSum, accumSum[windowEnd + 1] - accumSum[windowStart]);
            lastIndex[element] = windowEnd;
        }
        return maxSum;
    }
}

The provided Java code implements a solution to find the maximum score of a unique subarray from a given array of integers. The objective is to select a contiguous subarray such that no value appears more than once, and its sum is the highest possible. The approach taken can be summarized as follows:

  • Initialize an array lastIndex to store the last occurrence index of each element within the range of potential values in the elements array. The length of lastIndex is set to a constant maxVal, considering the maximum possible value in the elements array +1 to handle the indexing conveniently.
  • Utilize an auxiliary array accumSum to hold the accumulative sum of the elements, which aids in efficiently calculating the sum of any subarray.
  • Use two pointers, windowStart and windowEnd, to manage the sliding window's bounds.
  • Iterate through the elements using windowEnd. During each iteration:
    • Update the accumulative sum in accumSum.
    • If the current element has appeared earlier (i.e., its index is recorded in lastIndex), adjust windowStart to ensure all elements in the current window are unique.
    • Calculate the current subarray's sum by subtracting the accumulative sum at windowStart from the accumulative sum at windowEnd + 1. Update maxSum if the current subarray's sum is greater.
    • Update the lastIndex of the current element to the current windowEnd to track its most recent appearance.
  • The algorithm ultimately returns maxSum, which is the maximum sum of any unique subarray found during the iteration.

This approach efficiently tracks and updates the required values using a combination of auxiliary data structures and a sliding window technique, ensuring that each element contributes to at most one unique subarray in consideration for the maximum sum.

Comments

No comments yet.