Frequency of the Most Frequent Element

Medium

Topics
ArrayBinary SearchGreedySliding WindowPrefix SumSorting

You may perform at most k operations, each of which adds 1 to any single element of nums.

Return the largest number of equal elements you can end up with — the highest frequency of any one value after spending at most k in total.

Example 1

sorted102142all become 4
cost to raise each320
raised to 4
Spending at most k = 5 makes 3 elements equal here, at the value 4. Operations only ever add, so a group can only be levelled up to its own largest member — the target is never a free choice. Raising the braced group costs 5 in total, which is what fits inside the budget; widening it by one more element would not.
The values are shown sorted, which is not the input order; only the multiset matters.
Input:  nums = [1,2,4], k = 5
Output: 3
Explanation: Raise 1 to 4 for 3 and 2 to 4 for 2, spending all 5 and making every element 4.

Example 2

sorted104182133all become 4
cost to raise each3000
raised to 4left alone
Input:  nums = [1,4,8,13], k = 5
Output: 2
Explanation: Raising 4 to 8 costs 4, giving two 8s. Three equal elements would cost more than 5.

Example 3

sorted306192all become 3
cost to raise each000
raised to 3left alone
Input:  nums = [3,9,6], k = 2
Output: 1
Explanation: No pair can be brought together for 2 or less, so the best is a single element.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Operations only ever add, so a group of elements can be made equal only by raising them all to the largest value in the group. That one observation removes most of the search: the target value is never something you choose freely, it is the maximum of whichever elements you group.

Once the values are sorted, a group worth considering is always a contiguous run. If two elements are in the group, anything between them is cheaper to raise than the lower of the two, so including it is never worse.

The cost of making the run nums[i..j] all equal to nums[j] is nums[j] * (j - i + 1) minus the sum of the run — the area between a flat line at the top and the values underneath it.

That cost grows as the run widens and shrinks as it narrows, so a window that extends on the right and retreats on the left whenever the cost exceeds k finds the widest affordable run without ever backtracking. The answer is the widest window seen.

Approach

  1. Sort nums ascending.
  2. Run a window over it, keeping the sum of the values inside.
  3. Extend the window one element to the right, adding to the sum.
  4. The cost of levelling the window is nums[right] * window_width - window_sum.
  5. While that cost exceeds k, drop the leftmost element from the window and subtract it from the sum.
  6. Track the widest width the window ever reaches, and return it.

Walkthrough

nums = [1,4,8,13], k = 5
sorted already

   right = 0, window [1]
      cost = 1*1 - 1 = 0 <= 5     width 1

   right = 1, window [1,4]
      cost = 4*2 - 5 = 3 <= 5     width 2

   right = 2, window [1,4,8]
      cost = 8*3 - 13 = 11 > 5
      drop the 1 -> window [4,8]
      cost = 8*2 - 12 = 4 <= 5    width 2

   right = 3, window [4,8,13]
      cost = 13*3 - 25 = 14 > 5
      drop the 4 -> window [8,13]
      cost = 13*2 - 21 = 5 <= 5   width 2

widest width 2, answer 2

nums = [1,2,4], k = 5
   right = 2, window [1,2,4]
      cost = 4*3 - 7 = 5 <= 5     width 3
   answer 3

why the target is always the window maximum
   values can only go UP. To make a group equal you must
   lift everyone to the top of the group; aiming higher
   than the group maximum costs strictly more for every
   member and buys nothing.

Complexity

  • Time — O(n log n): the sort dominates; the window itself advances each index at most once on each side.
  • Space — O(log n) to O(n), and it is all the sort: the sliding window holds a running sum and two indices, so O(1) of its own. Since the sort already dominates the time, it is worth being exact about its memory too: Arrays.sort(int[]) in Java and std::sort in C++ sort in place but recurse, costing O(log n) of stack, while Python's list.sort() is Timsort and allocates an O(n) merge buffer.

Common Pitfalls

  • Forgetting to sort. The contiguous-run argument depends on the order.
  • Choosing a target value other than the window maximum. Operations only add, so nothing below the maximum is reachable.
  • Computing the cost as sum - value * width, with the sign the wrong way round.
  • Letting the cost product overflow a 32-bit integer. With values and widths both up to 100000 it exceeds it.
  • Returning the target value rather than how many elements share it.

Full Solution — all languages

class Solution:
    def maxFrequency(self, nums, k):
        nums.sort()

        best = 1
        left = 0
        window_sum = 0

        for right, value in enumerate(nums):
            window_sum += value

            # Cost of lifting the whole window up to nums[right].
            while value * (right - left + 1) - window_sum > k:
                window_sum -= nums[left]
                left += 1

            best = max(best, right - left + 1)

        return best
SensAI
Beta
Tap the mic to stop voice mode