Frequency of the Most Frequent Element (LeetCode 1838): Solution and Explanation
You may add 1 to any element at most k times in total. Find the largest number of equal elements you can end up with. After sorting, the answer is the longest window whose values can all be raised to its largest value within the budget.
Intuition
Operations only increase values, so a group of equal elements must end at the value of its largest member. Raising that member any higher just wastes operations.
Fix a target value nums[right]. Which other elements should join it? The ones closest below it, because they need the fewest +1 steps. After sorting, those are exactly the elements just to the left of right, so every candidate group is a contiguous window nums[left..right].
Raising the whole window to nums[right] costs nums[right] * (right - left + 1) - sum(window): the area between the target line and the bar tops. When right moves forward the target only grows, so a left that was too expensive stays too expensive. That monotonic behaviour is what makes a sliding window work.
Approach: Sort + sliding window on the raise cost
- Sort
numsin ascending order. - Keep
left = 0, the window sumtotal = 0andbest = 0. - For each
right, addnums[right]tototal. - While
nums[right] * (right - left + 1) - total > k, subtractnums[left]fromtotaland moveleftforward. - Update
bestwithright - left + 1, and return it at the end.
Step-by-step example
nums = [1,2,4], k = 5
- Sorted: [1,2,4].
- right = 0: window [1], cost 1 * 1 - 1 = 0. best = 1.
- right = 1: window [1,2], cost 2 * 2 - 3 = 1. best = 2.
- right = 2: window [1,2,4], cost 4 * 3 - 7 = 5, which is exactly k. best = 3.
- The answer is 3: all three values become 4.
Code: Python, Java, C++
1class Solution:
2 def maxFrequency(self, nums: List[int], k: int) -> int:
3 nums.sort()
4 left = 0
5 total = 0
6 best = 0
7 for right in range(len(nums)):
8 total += nums[right]
9 while nums[right] * (right - left + 1) - total > k:
10 total -= nums[left]
11 left += 1
12 best = max(best, right - left + 1)
13 return best1class Solution {
2 public int maxFrequency(int[] nums, int k) {
3 Arrays.sort(nums);
4 int left = 0, best = 0;
5 long total = 0;
6 for (int right = 0; right < nums.length; right++) {
7 total += nums[right];
8 while ((long) nums[right] * (right - left + 1) - total > k) {
9 total -= nums[left];
10 left++;
11 }
12 best = Math.max(best, right - left + 1);
13 }
14 return best;
15 }
16}1class Solution {
2public:
3 int maxFrequency(vector<int>& nums, int k) {
4 sort(nums.begin(), nums.end());
5 int left = 0, best = 0;
6 long long total = 0;
7 for (int right = 0; right < (int)nums.size(); right++) {
8 total += nums[right];
9 while ((long long)nums[right] * (right - left + 1) - total > k) {
10 total -= nums[left];
11 left++;
12 }
13 best = max(best, right - left + 1);
14 }
15 return best;
16 }
17};Time and space complexity
O(n log n)
Sorting dominates. The window itself is O(n) because left and right each move forward at most n times.
O(1)
Only a few counters besides the in-place sort (which may use O(log n) stack in some languages).
Other approaches
Binary search on prefix sums (time O(n log n), space O(n))
Build prefix sums of the sorted array, then for each right binary search the smallest left whose raise cost fits in k. Correct, but the sliding window removes the log factor.
Try every window (time O(n^2), space O(1))
For every pair (left, right) compute the cost directly. Easy to reason about, but quadratic or worse and far too slow for 10^5 elements.
Common mistakes
- Forgetting to sort. On the unsorted array a window is not the cheapest group for its target.
- Integer overflow:
nums[right] * (right - left + 1)can reach 10^10, so use a 64-bit type in Java, C++ and C#. - Raising toward the smallest value instead of the largest. Only increments are allowed.
- Using
>=instead of>in the shrink condition, which rejects windows whose cost is exactly k.
Frequently asked questions
Why should the target always be an existing value?
Picking a target between two values, or above the largest member, only adds operations without adding members. So the best group always ends at one of its own values.
Why never move left backwards?
When right moves forward the target value does not shrink and the window grows, so the cost of keeping any earlier left only goes up. A left that was too expensive before is still too expensive.
What is the time and space complexity?
O(n log n) time for the sort plus O(n) for the window, and O(1) extra space apart from sorting.
Can the window shrink by more than one step at a time?
Yes. A big jump in the target value can make several small values too expensive at once, so the shrink is a while loop, not a single if.