SDE & MLE Prep

1838. Frequency of the Most Frequent Element

Problem

One operation adds 1 to any element of nums. With at most k operations, return the highest possible frequency of a single value.

Example: nums = [1,2,4], k = 5 → 3 (raise 1 and 2 to 4); nums = [1,4,8,13], k = 5 → 2

Constraints: n ≤ 10⁵.

Sort. A window [l, r] can all be raised to nums[r] iff nums[r]·len − sum ≤ k. Shrink when it isn't.

Complexity: O(n log n).

class Solution:
    def maxFrequency(self, nums: List[int], k: int) -> int:
        nums.sort()
        l = s = best = 0
        for r, x in enumerate(nums):
            s += x
            while x * (r - l + 1) - s > k:
                s -= nums[l]
                l += 1
            best = max(best, r - l + 1)
        return best