Input: nums =[1,4,5], k =1, numOperations =2Output: 2Explanation:
We can achieve a maximum frequency of two by:* Adding 0 to `nums[1]`.`nums` becomes `[1, 4, 5]`.* Adding -1 to `nums[2]`.`nums` becomes `[1, 4, 4]`.
To maximize the frequency of any element after performing up to numOperations operations (each changing a different index by at most k), we want to make as many elements as possible equal to some value. By sorting the array, we can use a sliding window to efficiently check, for each possible target, how many elements can be made equal to it within the allowed operations.
classSolution {
public:int maxFrequency(vector<int>& nums, int k, int numOperations) {
sort(nums.begin(), nums.end());
longlong sum =0;
int l =0, ans =1, n = nums.size();
for (int r =0; r < n; ++r) {
sum += nums[r];
while ((longlong)nums[r] * (r - l +1) - sum > (longlong)numOperations * k) {
sum -= nums[l++];
}
ans = max(ans, r - l +1);
}
return ans;
}
};
classSolution {
publicintmaxFrequency(int[] nums, int k, int numOperations) {
Arrays.sort(nums);
long sum = 0;
int l = 0, ans = 1, n = nums.length;
for (int r = 0; r < n; r++) {
sum += nums[r];
while ((long)nums[r]* (r - l + 1) - sum > (long)numOperations * k) {
sum -= nums[l++];
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funmaxFrequency(nums: IntArray, k: Int, numOperations: Int): Int {
nums.sort()
var sum = 0Lvar l = 0var ans = 1for (r in nums.indices) {
sum += nums[r]
while (nums[r].toLong() * (r - l + 1) - sum > numOperations.toLong() * k) {
sum -= nums[l++]
}
ans = maxOf(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, numOperations: int) -> int:
nums.sort()
l =0 s =0 ans =1for r, v in enumerate(nums):
s += v
while nums[r] * (r - l +1) - s > numOperations * k:
s -= nums[l]
l +=1 ans = max(ans, r - l +1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnmax_frequency(nums: Vec<i32>, k: i32, num_operations: i32) -> i32 {
letmut nums = nums;
nums.sort();
letmut sum =0i64;
letmut l =0;
letmut ans =1;
for r in0..nums.len() {
sum += nums[r] asi64;
while (nums[r] asi64) * (r asi64- l asi64+1) - sum > (num_operations asi64) * (k asi64) {
sum -= nums[l] asi64;
l +=1;
}
ans = ans.max(r asi32- l asi32+1);
}
ans
}
}