Apply Operations to Maximize Frequency Score - Problem

You are given a 0-indexed integer array nums and an integer k.

You can perform the following operation on the array at most k times:

  • Choose any index i from the array and increase or decrease nums[i] by 1.

The score of the final array is the frequency of the most frequent element in the array.

Return the maximum score you can achieve.

The frequency of an element is the number of occurrences of that element in the array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,6,1], k = 3
Output: 3
💡 Note: We can make [1,2,6,1] → [2,2,2,1] using 3 operations: change first 1→2 (1 op), change 6→2 (4 ops), but that exceeds k=3. Better: make [1,1,2] all equal to 2 with cost (2-1)+(2-1)+(2-2)=2≤3, giving frequency 3.
Example 2 — All Elements Same
$ Input: nums = [3,9,6], k = 2
Output: 1
💡 Note: To make any 2 elements equal: min cost is |3-6|=3 or |3-9|=6 or |6-9|=3, all > k=2. So we can only achieve frequency 1.
Example 3 — Large Budget
$ Input: nums = [1,1,2,2], k = 4
Output: 4
💡 Note: We can make all elements equal to 2: change two 1s to 2s costs 2 operations total. All 4 elements become 2, so frequency = 4.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 2 × 1014

Visualization

Tap to expand
Apply Operations to Maximize Frequency ScoreInput:1261k = 3 operationsSort & Transform:2226Cost: (2-1) + (2-1) + (2-2) = 2 ≤ 3 operationsOutput: Maximum frequency = 3
Understanding the Visualization
1
Input
Array [1,2,6,1] with k=3 operations
2
Process
Sort and find optimal group of elements to unify
3
Output
Maximum frequency of 3 by making [1,1,2] all equal to 2
Key Takeaway
🎯 Key Insight: Sort first, then sliding window finds the largest group of elements that can be unified within the operation budget
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 5
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen