[LeetCode] Frequency of the Most Frequent Element

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;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/25/PS/LeetCode/frequency-of-the-most-frequent-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.