Frequency of the Most Frequent Element
Add 1 to values at most k times in total and find the highest count one value can reach.
The frequency of a value is how many times it appears in an array. Given an integer array numskk
Example 1
Output: 3
Explanation: add 3 to the 1 and 2 to the 2, giving [4, 4, 4].
Example 2
Output: 2
Explanation: for example, add 3 to the 1 to get two 4s.
Example 3
Output: 1
The Idea
Picture four stacks of blocks, 1, 4, 8 and 13 blocks tall, and 5 spare blocks. You may put spare blocks on any stack, but you can never take blocks away. How many stacks can you make the same height? That is Example 2: each spare block is one "add 1", and stacks of the same height are copies of one value.
Try a few choices. Putting 3 blocks on the 1 makes it 4, so there are two stacks of 4. Putting 5 blocks on the 8 gives two stacks of 13. The cheapest way to get three equal stacks raises the 1 and the 4 to 8, and that takes 7 + 4 = 11 blocks, more than 5. So the answer is 2.
With four stacks we can try everything by hand, but with thousands we cannot. Which values should be made equal, and to what height?
The height is always one of the values already there. Values can only grow, so the largest of the chosen values cannot come down, and the others are raised to meet it. Raising all of them past it would only cost more. And for a given target, the cheapest values to raise are the ones just below it. So sort the array: the best group for each target is then a run of neighbours that ends at the target. Such a run of neighbouring positions is called a window.
How much does a window cost, counting each added 1 as one step? Look at the picture below, which shows Example 1, the window 1, 2, 4 raised to its largest value, 4.
The 1 needs +3 and the 2 needs +2, the dashed orange parts. Together with the blue bars they fill the dashed rectangle, which is 4 high and 3 bars wide, so it holds 4 × 3 = 12. The bars now hold 1 + 2 + 4 = 7, and the orange part is what is left: 12 - 7 = 5. That is at most k = 5, so all three can become 4.
So the cost of a window is its largest value times its size, minus the sum of its values. One multiplication and one subtraction, with no need to look at each value.
Solution Approach
Turning that idea into code means settling four things: how to search the windows, how to get a window's cost quickly, what to do when a window costs too much, and how to keep the numbers from overflowing.
Searching the windows
What is the simple way to search? Try every value as the target, and grow a window to its left until the cost passes k
A sliding window does it in one pass. Two markers, leftrightrightleft
Keeping the cost up to date
How do we get a window's cost without adding up its values every time? Keep a running total, sumrightsumleftnums[right] × (right - left + 1) - sumright - left + 1
Shrinking a window that costs too much
What if the cost is more than kleft
Could the dropped value be needed again later? No. Every later window that starts at it has a larger or equal target and at least as many values to raise, so it costs even more than k
Here is Example 2, sorted as 1, 4, 8, 13. With rightrightright
Avoiding overflow
Can the numbers get too big? With 100,000 values of 100,000 each, both sumintintsumlonglong
Java Solution
The method maxFrequency
- First, sort the array with
, so the cheapest values to raise to a target sit just before it.Arrays.sort(nums) - Set up the window:
starts at 0, theleftlong starts at 0, andsum , the largest window size seen so far, starts at 0.best - A
loop movesfor from the first position to the last, and adds eachright tonums[right] .sum - Inside it, a
loop computes the cost,while . While the cost is more than(long) nums[right] * (right - left + 1) - sum , it subtractsk fromnums[left] and movessum one place forward.left - The window now fits within
, so its size,k , is a frequency we can reach. Keep the larger of it andright - left + 1 .best - When the
loop ends, returnfor .best
The maink = 0int
import java.util.Arrays;
public class FrequencyOfTheMostFrequentElement {
public static int maxFrequency(int[] nums, int k) {
Arrays.sort(nums);
int left = 0;
long sum = 0; // sum of nums[left..right]
int best = 0;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
// raising every value in the window to nums[right] costs size * nums[right] - sum
while ((long) nums[right] * (right - left + 1) - sum > k) {
sum -= nums[left]; // drop the smallest value
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println(maxFrequency(new int[] {1, 2, 4}, 5));
System.out.println(maxFrequency(new int[] {1, 4, 8, 13}, 5));
System.out.println(maxFrequency(new int[] {3, 9, 6}, 2));
System.out.println(maxFrequency(new int[] {7}, 0));
System.out.println(maxFrequency(new int[] {3, 2, 3, 2, 3}, 0));
int[] big = new int[100000]; // 50,000 ones, then 50,000 copies of 100,000
Arrays.fill(big, 0, 50000, 1);
Arrays.fill(big, 50000, 100000, 100000);
System.out.println(maxFrequency(big, 1));
}
}
Running it prints:
3
2
1
1
3
50000
The 3, 2 and 1 at the top match the three examples. Example 3 gives 1 because its sorted values are 3, 6, 9, and raising 3 to 6 already costs 3, more than k = 2[3, 2, 3, 2, 3]k = 0
The last line, 50000, is the large array: 50,000 ones, then 50,000 copies of 100,000, with k = 1longintint
The original implementation,
Complexity
The work is the sort, then one pass in which rightleft
- Time: O(n log n), because sorting the n values takes O(n log n). The window pass after it is only O(n):
visits each value once, andright moves forward at most n times in total.left - Space: O(1) besides the sort. The window keeps only
,left ,right andsum , however long the array is.best