Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Sorting + Sliding Window Technique
In e.g.1, we were lucky, that array was sorted. So, we can easily see where we are allocating our budget k to elements in array to make them most frequent.
Finding difference between 2 elements is easier to find in sorted array.
- First sort the array
nums. - In order to calculate the maximum frequency of a number, we can increment some numbers less than it. Let this number be
x. - Let
lis left pointer andris right pointer. Window sizesize = (r-l+1) - We assume number we are finding is on right pointer, and we allocate budget
kto numbers smaller than it. When all numbers in window becomex, total sum here should bex*size. Suppose, all the numbers which are part of solution add up tosum. Then this condition holds:k + sum >= size * xk+sum[r:l] >= (r-l+1) * nums[r]nums[r] * (r-l+1) - sums[r:l] <=kBecause if it is less, we are out ofk, our budget. - Our answer is window size.
Also, remember to use long for sums, to avoid overflow.
Code
| |
Complexity
Now problem becomes O(n log n) + O(n) = O(n log n)