The frequency of an element is the number of occurrences of that element in an array.
I give you an integer array nums and an integer k. In a single operation, you can select a subscript of NUMs and increment the value of the corresponding element by 1.
Returns the maximum possible frequency of the highest frequency element in the array after performing a maximum of k operations.
Example 1:
Input: nums = [1,2,4], k = 5 output: 3 description: increment the first element three times and increment the second element two times, nums = [4,4,4]. Four is the highest frequency element in the array, frequency three. Example 2:
Input: nums = [1,4,8,13], k = 5 output: 2 explanation: there are multiple optimal solutions:
- Incrementing the first element three times, nums = [4,4,8,13]. Four is the highest frequency element in the array, frequency two.
- Incrementing the second element four times, nums = [1,8,8,13]. Eight is the highest frequency element in the array, frequency two.
- Incrementing the third element five times, nums = [1,4,13,13]. 13 is the highest frequency element in the array, frequency 2.
Example 3:
Input: nums = [3,9,6], k = 2 output: 1
Their thinking
Sort the array, use the sliding window, the element in the window is represented, after the maximum k operation, can produce all the elements in the window increment to NUMS [r], traverse the right boundary, generate several Windows that meet the conditions, find the largest window, the length of the window is the maximum possible frequency
code
class Solution {
public int maxFrequency(int[] nums, int k) {
Arrays.sort(nums);
int l=0,r=0,n=nums.length,sum=0,max=0;
if(n==1) return 1;
while (r<n-1)
{
r++;
sum+=(r-l)*(nums[r]-nums[r-1]);
while(sum>k) { sum-=nums[r]-nums[l]; l++; } max= Math.max(max,r-l+1);
}
returnmax; }}Copy the code