Maximum Unique Subarray Sum After Deletion Problem
#3487
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3487.
You are given an integer array nums.
You are allowed to delete any number of elements from nums without making it empty. After performing the deletions, select a subarray of nums such that:
- All elements in the subarray are unique.
- The sum of the elements in the subarray is maximized.
Return the maximum sum of such a subarray.
Example 1:
Input: nums = [1,2,3,4,5]
Output: 15
Explanation:
Select the entire array without deleting any element to obtain the maximum sum.
Example 2:
Input: nums = [1,1,0,1,1]
Output: 1
Explanation:
Delete the element nums[0] == 1, nums[1] == 1, nums[2] == 0, and nums[3] == 1. Select the entire array [1] to obtain the maximum sum.
Example 3:
Input: nums = [1,2,-1,-2,1,0,-1]
Output: 3
Explanation:
Delete the elements nums[2] == -1 and nums[3] == -2, and select the subarray [2, 1] from [1, 2, 1, 0, -1] to obtain the maximum sum.
Constraints:
1 <= nums.length <= 100-100 <= nums[i] <= 100
Solution
Approach: Greedy with a Set
Because we may delete any elements before choosing the subarray, we can end up with any subsequence whose values are distinct (after deleting, the kept elements become contiguous). So we want a set of distinct values with the largest possible sum, and it must be non-empty.
- If the largest element is not positive, adding anything only lowers the sum, so the best choice is that single largest element.
- Otherwise take every distinct positive value exactly once and skip the rest.
Walk through the array, keeping a set of positive values already added.
Complexity: O(n) time and O(n) extra space.
class Solution:
def maxSum(self, nums: List[int]) -> int:
mx = max(nums)
if mx <= 0:
return mx
ans = 0
s = set()
for x in nums:
if x < 0 or x in s:
continue
ans += x
s.add(x)
return ans