#1838
Medium Algorithms Frequency of the most frequent element
Array Binary Search Greedy Sliding Window Sorting Prefix Sum
44.6% acceptance
Feb 25, 2026
5701
305
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn max_frequency(mut nums: Vec<i32>, k: i32) -> i32 {
nums.sort_unstable();
let n = nums.len();
let mut l = 0usize;
let mut window_sum: i64 = 0;
let mut result = 1;
for r in 0..n {
window_sum += nums[r] as i64;
// Cost to make all elements in [l..=r] equal to nums[r]
while nums[r] as i64 * (r - l + 1) as i64 - window_sum > k as i64 {
window_sum -= nums[l] as i64;
l += 1;
}
result = result.max((r - l + 1) as i32);
}
result
}
}