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
Solutions
Solution 1: Array or Hash Table + Prefix Sum
Thinking
We want the maximum sum of a contiguous subarray of distinct values. \(n\) is \(10^5\); the last-seen index pushes the left end \(j\) past duplicates, and prefix sums give the range sum.
Array \(d\) stores the latest index of each value. On \(v\), set \(j=\max(j,d[v])\) and update with \(s[i]-s[j]\).
We use an array or hash table \(\text{d}\) to record the last occurrence position of each number, and use a prefix sum array \(\text{s}\) to record the sum from the starting point to the current position. We use a variable \(j\) to record the left endpoint of the current non-repeating subarray.
We iterate through the array. For each number \(v\), if \(\text{d}[v]\) exists, we update \(j\) to \(\max(j, \text{d}[v])\), which ensures that the current non-repeating subarray does not contain \(v\). Then we update the answer to \(\max(\text{ans}, \text{s}[i] - \text{s}[j])\), and finally update \(\text{d}[v]\) to \(i\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\text{nums}\).
Solution 1 uses prefix sums and an index table. A sliding window can store the live distinct sum: shrink from the left on a duplicate and skip the prefix array.
The problem is essentially asking us to find the longest subarray where all elements are distinct. We can use two pointers \(i\) and \(j\) to point to the left and right boundaries of the subarray, initially \(i = 0\) and \(j = 0\). Additionally, we use a hash table \(\text{vis}\) to record the elements in the subarray.
We iterate through the array. For each number \(x\), if \(x\) is in \(\text{vis}\), we continuously remove \(\text{nums}[i]\) from \(\text{vis}\) until \(x\) is no longer in \(\text{vis}\). This way, we find a subarray that contains no duplicate elements. We add \(x\) to \(\text{vis}\), update the subarray sum \(s\), and then update the answer \(\text{ans} = \max(\text{ans}, s)\).
After the iteration, we can get the maximum subarray sum.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\text{nums}\).