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).
To find the maximum sum of a subarray with all unique elements, we use a sliding window to maintain a range of non-repeating numbers. By expanding the window to the right and shrinking it from the left when duplicates are found, we can efficiently track the sum of unique elements and update the answer.
classSolution {
public:int maximumUniqueSubarray(vector<int>& nums) {
unordered_set<int> set;
int ans =0, sum =0, left =0;
for (int right =0; right < nums.size(); ++right) {
while (set.count(nums[right])) {
set.erase(nums[left]);
sum -= nums[left++];
}
set.insert(nums[right]);
sum += nums[right];
ans = max(ans, sum);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcmaximumUniqueSubarray(nums []int) int {
set:= make(map[int]bool)
ans, sum, left:=0, 0, 0forright:=0; right < len(nums); right++ {
forset[nums[right]] {
set[nums[left]] = falsesum-=nums[left]
left++ }
set[nums[right]] = truesum+=nums[right]
ifsum > ans {
ans = sum }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintmaximumUniqueSubarray(int[] nums) {
Set<Integer> set =new HashSet<>();
int ans = 0, sum = 0, left = 0;
for (int right = 0; right < nums.length; right++) {
while (set.contains(nums[right])) {
set.remove(nums[left]);
sum -= nums[left++];
}
set.add(nums[right]);
sum += nums[right];
ans = Math.max(ans, sum);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funmaximumUniqueSubarray(nums: IntArray): Int {
val set = mutableSetOf<Int>()
var ans = 0var sum = 0var left = 0for (right in nums.indices) {
while (nums[right] inset) {
set.remove(nums[left])
sum -= nums[left]
left++ }
set.add(nums[right])
sum += nums[right]
ans = maxOf(ans, sum)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type Solution:
defmaximumUniqueSubarray(self, nums: list[int]) -> int:
set_: set[int] = set()
ans: int =0 sum_: int =0 left: int =0for right in range(len(nums)):
while nums[right] in set_:
set_.remove(nums[left])
sum_ -= nums[left]
left +=1 set_.add(nums[right])
sum_ += nums[right]
ans = max(ans, sum_)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnmaximum_unique_subarray(nums: Vec<i32>) -> i32 {
use std::collections::HashSet;
letmut set = HashSet::new();
let (mut ans, mut sum, mut left) = (0, 0, 0);
for right in0..nums.len() {
while set.contains(&nums[right]) {
set.remove(&nums[left]);
sum -= nums[left];
left +=1;
}
set.insert(nums[right]);
sum += nums[right];
ans = ans.max(sum);
}
ans
}
}