Maximum Erasure Value
MedPrompt
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 <= 1051 <= nums[i] <= 104
Approaches
3 approaches with complexity analysis and trade-offs.
This is the most straightforward but naive approach. The idea is to generate every possible contiguous subarray of the input array nums. For each of these subarrays, we first check if it contains only unique elements. If it does, we then calculate its sum and update the maximum score found so far if the current sum is greater.
Algorithm
- Initialize
maxScoreto 0. - Use a nested loop to generate all possible start
iand endjindices of a subarray. - For each subarray
nums[i...j], create a third loop fromk = itoj. - Inside the third loop, use a
HashSetto check for uniqueness. If a duplicate is found, the subarray is invalid. - If the subarray is unique after checking all its elements, calculate its sum.
- Update
maxScore = max(maxScore, currentSum). - After all subarrays are checked, return
maxScore.
Walkthrough
We can implement this using three nested loops. The outer two loops, with indices i and j, define the start and end of a subarray. The third loop, with index k, iterates through this subarray nums[i...j]. Inside this innermost loop, we use a HashSet to keep track of the elements we've seen in the current subarray. If we encounter an element that's already in the set, we know the subarray is not unique. If the loop completes without finding duplicates, we calculate the sum and update our global maximum score. This process is repeated for all O(n^2) possible subarrays.
import java.util.HashSet;import java.util.Set; class Solution { public int maximumUniqueSubarray(int[] nums) { int maxScore = 0; for (int i = 0; i < nums.length; i++) { for (int j = i; j < nums.length; j++) { Set<Integer> uniqueElements = new HashSet<>(); int currentSum = 0; boolean isUnique = true; // Check for uniqueness and calculate sum for subarray nums[i...j] for (int k = i; k <= j; k++) { if (!uniqueElements.add(nums[k])) { isUnique = false; break; } currentSum += nums[k]; } if (isUnique) { maxScore = Math.max(maxScore, currentSum); } } } return maxScore; }}Complexity
Time
O(n^3). There are O(n^2) subarrays, and for each subarray, we iterate through its elements to check for uniqueness and calculate the sum, which takes up to O(n) time.
Space
O(n), as the `HashSet` can store up to `n` elements for a subarray of length `n`.
Trade-offs
Pros
Simple to understand and conceptualize.
Cons
Extremely inefficient due to three nested loops.
Will result in a 'Time Limit Exceeded' error on any reasonably sized input.
Solutions
Solution
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: d = defaultdict(int) s = list(accumulate(nums, initial=0)) ans = j = 0 for i, v in enumerate(nums, 1): j = max(j, d[v]) ans = max(ans, s[i] - s[j]) d[v] = i return ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.