Frequency of the Most Frequent Element LeetCode solution in C++

1
#define ll long long
2

3
class Solution {
4
public:
5
int maxFrequency(vector<int> &nums, int k) {
6
// sorting so that can easily find the optimal window
7
sort(nums.begin(), nums.end());
8

9
// left - left pointer of window
10
// right - right pointer of window
11
int left = 0, right = 0, ans = 1;
12
ll total = 0, n = nums.size();
13
while (right < n) {
14
// total - total sum of elements in the window
15
total += nums[right];
16

17
// Checking if the we can achieve elements in this window
18
// If it exceeds k then shrinking the window by moving left pointer
19
// For optimal we will make all elements in the array equal to
20
// the maximum value element
21
while ((1ll) * (right - left + 1) * nums[right] - total > k) {
22
total -= nums[left];
23
left++;
24
}
25

26
ans = max(ans, right - left + 1);
27
right++;
28
}
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0