1838. Frequency of the Most Frequent Element
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: int maxFrequency(vector<int>& nums, long k) { sort(nums.begin(), nums.end()); long end = 0, sz = nums.size(), res = 0; for(int front = 0; front < sz && end < sz; front++) { while(end < sz && k >= 0) { res = max(res, end - front + 1); end++; if(end != sz) k -= (end - front) * (nums[end] - nums[end - 1]); } if(end != sz) k += (nums[end] - nums[front]); } return res; } };
|