Input: nums =[1,2,6,4], k =3Output: 3Explanation: We can do the following operations on the array:- Choose i =0, and increase the value of nums[0] by 1. The resulting array is[2,2,6,4].- Choose i =3, and decrease the value of nums[3] by 1. The resulting array is[2,2,6,3].- Choose i =3, and decrease the value of nums[3] by 1. The resulting array is[2,2,6,2].The element 2is the most frequent in the final array so our score is3.It can be shown that we cannot achieve a better score.
Input: nums =[1,4,4,2,4], k =0Output: 3Explanation: We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is3.
The key idea is to maximize the frequency of any number by making as many elements equal to it as possible, using at most k operations. By sorting the array, we can efficiently use a sliding window to check, for each possible target value, how many elements can be converted to it within the allowed number of operations.
For each right pointer, try to expand the window as much as possible such that the total cost to make all elements in the window equal to nums[right] does not exceed k.
The cost is calculated as the sum of differences between nums[right] and all elements in the window.
If the cost exceeds k, move the left pointer to shrink the window.
Track the maximum window size (i.e., frequency) achieved.
classSolution {
public:int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
longlong total =0;
int l =0, ans =1;
for (int r =0; r < nums.size(); ++r) {
total += nums[r];
while ((longlong)nums[r] * (r - l +1) - total > k) {
total -= nums[l++];
}
ans = max(ans, r - l +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintmaxFrequency(int[] nums, int k) {
Arrays.sort(nums);
long total = 0;
int l = 0, ans = 1;
for (int r = 0; r < nums.length; r++) {
total += nums[r];
while ((long)nums[r]* (r - l + 1) - total > k) {
total -= nums[l++];
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmaxFrequency(self, nums: list[int], k: int) -> int:
nums.sort()
total =0 l =0 ans =1for r, val in enumerate(nums):
total += val
while val * (r - l +1) - total > k:
total -= nums[l]
l +=1 ans = max(ans, r - l +1)
return ans