[LeetCode] Maximum Sum of Almost Unique Subarray

2841. Maximum Sum of Almost Unique Subarray

You are given an integer array nums and two positive integers m and k.

Return the maximum sum out of all almost unique subarrays of length k of nums. If no such subarray exists, return 0.

A subarray of nums is almost unique if it contains at least m pairwise distinct elements.

A subarray is a contiguous non-empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
long long maxSum(vector<int>& nums, int m, int k) {
long long res = 0, sum = 0;
unordered_map<int, int> freq;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];
freq[nums[i]] += 1;
if(i >= k) {
sum -= nums[i-k];
if(--freq[nums[i-k]] == 0) freq.erase(nums[i-k]);
}
if(i + 1 >= k and freq.size() >= m) {
res = max(res, sum);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/02/PS/LeetCode/maximum-sum-of-almost-unique-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.