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.

 

Example 1:

Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.

Example 2:

Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.

Example 3:

Input: nums = [3,9,6], k = 2
Output: 1

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= k <= 105

Rust Solution

struct Solution;

impl Solution {
    fn max_frequency(mut nums: Vec<i32>, k: i32) -> i32 {
        nums.sort_unstable();
        let n = nums.len();
        let mut i = 0;
        let mut j = 0;
        let mut sum = 0;
        let mut res = 0;
        while j < n {
            sum += nums[j];
            j += 1;
            while (j - i) as i32 * nums[j - 1] - sum > k {
                sum -= nums[i];
                i += 1;
            }
            res = res.max(j - i);
        }
        res as i32
    }
}

#[test]
fn test() {
    let nums = vec![1, 2, 4];
    let k = 5;
    let res = 3;
    assert_eq!(Solution::max_frequency(nums, k), res);
    let nums = vec![1, 4, 8, 13];
    let k = 5;
    let res = 2;
    assert_eq!(Solution::max_frequency(nums, k), res);
    let nums = vec![3, 9, 6];
    let k = 2;
    let res = 1;
    assert_eq!(Solution::max_frequency(nums, k), res);
}

Having problems with this solution? Click here to submit an issue on github.