problem:2841. 几乎唯一子数组的最大和
思路:定长滑动窗口的变形题
Accode:
class Solution {
public:
long long maxSum(vector<int>& nums, int m, int k) {
unordered_map<int,int> dict;
deque<int> deq;
long long sum = 0;
int len = nums.size();
long long ans = 0;
for(int i=0;i<len;i++){
if(deq.size() && i-deq.front()+1>k){
dict[nums[deq.front()]]--;
if(dict[nums[deq.front()]]==0) dict.erase(nums[deq.front()]);
sum-=nums[deq.front()];
deq.pop_front();
}
deq.push_back(i);
dict[nums[i]]++;
sum+=nums[i];
if(i+1>=k && dict.size()>=m){
ans = max(ans,sum);
}
}
return ans;
}
};
时间复杂度:$o(n)$