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.

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.
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.
Input: nums = [3,9,6], k = 2
Output: 1
Constraints:

Contents

In this approach, we are going to sort the input array first, then apply sliding window technique. The reason we will sort the array is because, the right most element of the window should be either equal or greater than the left side elements, so that we know the value to what we will make its left side elements to. For example, after sorting the input array is [1, 2, 5, 9, 11], say we are at window left =0, right =2, since we know right element is '5', we need to make left side elements in the same window to 5 as well to make that most frequent element in that window.

Implementation steps:
import java.util.Arrays; public class FrequencyOfTheMostFrequentElement { static int maxFrequency(int[] nums, int k) { Arrays.sort(nums); // O(n log n) int left = 0; int right=0; int maxFrequency = 0; long sum = 0; while(right < nums.length) { sum += nums[right]; /* window length * nums[right] --> this is the value if we make all of left side elements same as current element. sum +k --> cumulative sum, and we can distribute K among those numbers. if left side value is greater, then we won't be able to all of left side elements in current window to same as current element. So, we will shift the window. */ while((long) (right - left + 1) * nums[right] > sum+k) { sum -= nums[left]; left++; } maxFrequency = Math.max(maxFrequency, right-left+1); right++; } return maxFrequency; } public static void main(String[] args) { System.out.println(maxFrequency(new int[]{1,1,1,2,2,4}, 3)); System.out.println(maxFrequency(new int[]{1,4,8,13}, 5)); System.out.println(maxFrequency(new int[]{1,2,4}, 5)); System.out.println(maxFrequency(new int[]{3,9,6}, 2)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n log(n)) time, where n is the length of input array nums, because we are sorting the array.
Space complexity: O(1), assumming that sorting will be done in-place algorithms like QuickSort

Above implementations source code can be found at GitHub link for Java code