力扣2841.几乎唯一子数组的最大和
-
哈希表存数字出现次数 没了就erase
-
class Solution {public:long long maxSum(vector<int>& nums, int m, int k) {long long ans = 0, sum = 0;unordered_map<int,int> cnt;for(int i=0;i<k-1;i++){sum += nums[i];cnt[nums[i]] ++;}for(int i=k-1;i<nums.size();i++){sum += nums[i];cnt[nums[i]] ++;if(cnt.size() >= m)ans = max(ans,sum);int out = nums[i-k+1];sum -= out;if(-- cnt[out] == 0)cnt.erase(out); }return ans;}};