2841. 几乎唯一子数组的最大和
使用unordered_map;unordered_multiset可能也可以,但是不如前者方便
class Solution { public: long long maxSum(vector<int>& nums, int m, int k) { int size = nums.size(); long long now = 0; unordered_map<int,int> numAdded; for(int i = 0;i < k;i++){ now += nums[i]; numAdded[nums[i]]++;//如果原本没有这个键,那么就会添加,对应的值自增1 } long long resMax = 0;//题目说了,如果不存在几乎唯一子数组,请返回0 if(numAdded.size() >= m) resMax = now; for(int i = k;i < size;i++){ if(numAdded[nums[i-k]] == 1) numAdded.erase(nums[i-k]);//如果将要移出的元素在原本的unordered_map只剩下一个,直接从unordered_map中删除 else numAdded[nums[i-k]]--; now = now - nums[i-k] + nums[i]; numAdded[nums[i]]++; if(numAdded.size() >= m && now > resMax) resMax = now; } return resMax; } };
标签:resMax,nums,int,long,2841,数组,now,leetcode,numAdded From: https://www.cnblogs.com/uacs2024/p/18582028