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 nums and an integer k, you may pick an element and add 1 to it, at most k times in total, and the same element may be picked again. Return the highest frequency any value can reach.

Example 1
Input: nums = [1, 2, 4], k = 5
Output: 3
Explanation: add 3 to the 1 and 2 to the 2, giving [4, 4, 4].
Example 2
Input: nums = [1, 4, 8, 13], k = 5
Output: 2
Explanation: for example, add 3 to the 1 to get two 4s.
Example 3
Input: nums = [3, 9, 6], k = 2
Output: 1
Solution

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.

Bars of height 1, 2 and 4 raised to 4. The dashed rectangle holds 4 times 3 = 12, the bars hold 1 + 2 + 4 = 7, so the cost is 12 - 7 = 5, the dashed orange part: +3 on the 1 and +2 on the 2.

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. For an array of n values, that can take n steps for each of the n targets, about n² steps in all, or 1010 for 100,000 values.

A sliding window does it in one pass. Two markers, left and right, hold the first and last positions of the window. right moves through the sorted array one step at a time, and the value it reaches becomes the target. left also moves only forward, and only when the window costs too much.

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, sum, of the values in the window. When right takes in a value, add it to sum; when left lets one go, subtract it. The cost is then nums[right] × (right - left + 1) - sum, the formula from the picture, where right - left + 1 is the window's size.

Shrinking a window that costs too much

What if the cost is more than k? Then the window drops its first value, the smallest one and so the most expensive to raise, and left moves one place forward. This repeats until the cost fits.

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 right on 4, the window 1, 4 costs 4 × 2 - 5 = 3, which fits. With right on 8, the window 1, 4, 8 costs 8 × 3 - 13 = 11, so the 1 is dropped, and 4, 8 costs 8 × 2 - 12 = 4. With right on 13, the window 4, 8, 13 costs 13 × 3 - 25 = 14, so the 4 is dropped, and 8, 13 costs 13 × 2 - 21 = 5. Once each window fits, it never holds more than two values, which is the answer.

Avoiding overflow

Can the numbers get too big? With 100,000 values of 100,000 each, both sum and the product in the cost reach 1010, ten billion. An int stops at 2,147,483,647, about 2.1 billion, so these totals would not fit. Instead of failing, an int sum that passes that limit wraps around to large negative numbers and keeps counting from there; this is called overflow. So sum is a long, and the product is cast to long before multiplying.

Java Solution

The method maxFrequency works in these steps:

  1. First, sort the array with Arrays.sort(nums), so the cheapest values to raise to a target sit just before it.
  2. Set up the window: left starts at 0, the long sum starts at 0, and best, the largest window size seen so far, starts at 0.
  3. A for loop moves right from the first position to the last, and adds each nums[right] to sum.
  4. Inside it, a while loop computes the cost, (long) nums[right] * (right - left + 1) - sum. While the cost is more than k, it subtracts nums[left] from sum and moves left one place forward.
  5. The window now fits within k, so its size, right - left + 1, is a frequency we can reach. Keep the larger of it and best.
  6. When the for loop ends, return best.

The main method runs the three examples, a single value, an array where one value already appears three times and k = 0, and 100,000 values whose sum does not fit in an int.

Java
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:

Output
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. A single 7 is a frequency of 1 on its own. The 3 on the fifth line comes from [3, 2, 3, 2, 3] with k = 0: nothing can be raised, so the answer is how often 3 already appears.

The last line, 50000, is the large array: 50,000 ones, then 50,000 copies of 100,000, with k = 1. One step cannot raise a 1 to 100,000, so the best is the 50,000 copies already there. Here the long matters: with an int sum and an int product, the same method returns 92,950 for this array, because both totals overflow.

The original implementation, FrequencyOfTheMostFrequentElement.java, is on GitHub.

Complexity

The work is the sort, then one pass in which right and left each move forward through the array.

  • Time: O(n log n), because sorting the n values takes O(n log n). The window pass after it is only O(n): right visits each value once, and left moves forward at most n times in total.
  • Space: O(1) besides the sort. The window keeps only left, right, sum and best, however long the array is.

Sliding Window Basics explains the grow-and-shrink loop used here in more detail.