problem:1838. 最高频元素的频数
思路:滑动窗口维护窗口的操作数<=k
Accode:
class Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(),nums.end());
long long sum = 0;
int len = nums.size();
int ans = 0;
deque<int> deq;
for(int i=0,j=0;i<len;i++){
if(deq.size()) sum+=1LL*(nums[i]-nums[deq.back()])*(i-deq.front());
while(deq.size() && sum>k){
int curr = nums[deq.front()];
deq.pop_front();
sum-=nums[i]-curr;
}
deq.push_back(i);
ans = max(ans,(int)deq.size());
}
return ans;
}
};
时间复杂度:$o(n)$