[LeetCode] Maximum Unique Subarray Sum After Deletion

3487. Maximum Unique Subarray Sum After Deletion

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:

  1. All elements in the subarray are unique.
  2. The sum of the elements in the subarray is maximized.

Return the maximum sum of such a subarray.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxSum(vector<int>& nums) {
int res = *max_element(begin(nums), end(nums)), n = nums.size(), sum = 0;
unordered_set<int> us;
for(int i = 0; i < n; i++) {
if(us.count(nums[i])) continue;
us.insert(nums[i]);
sum += max(0,nums[i]);
}
return sum > 0 ? sum : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/25/PS/LeetCode/maximum-unique-subarray-sum-after-deletion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.