Frequency of the Most Frequent Element

After sorting, slide a window while the cost of raising all elements to the max ≤ k.

Medium
Time O(n log n) Space O(1)
LeetCode
4 min read
sliding-window sorting array

Problem#

In one operation increment any element by 1. With at most k operations, return the maximum possible frequency of any element.

Examples#

  • nums = [1,2,4], k = 53 (raise 1 to 4 with 3 ops, 2 to 4 with 2 ops)
  • nums = [1,4,8,13], k = 52

Constraints#

  • 1 <= nums.length <= 10^5, 1 <= k <= 10^5.

Hints#

Hint 1
Sort first. The most-frequent value will be the right end of some sorted window; cost = (r - l + 1) * nums[r] - prefixSum.

Approach#

Sort. Slide a window [l, r]; the right end is the target value. Cost to raise everything in the window to nums[r] is nums[r]*(r - l + 1) - sum(window). Shrink while cost > k.

Solution#

Frequency of the Most Frequent Element
class Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
long long sum = 0;
int left = 0, best = 1;
for (int right = 0; right < (int)nums.size(); ++right) {
sum += nums[right];
while ((long long)nums[right] * (right - left + 1) - sum > k) {
sum -= nums[left++];
}
best = max(best, right - left + 1);
}
return best;
}
};

Editorial#

Sorting unlocks the window: the cheapest way to make a group equal to v is to start from values ≤ v sorted by closeness. The cost formula target * count - sum is the prefix-sum identity. Cast to long long early — nums[right] * (right - left + 1) can overflow for the max constraints.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.