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 Score INPUT nums array: 1 i=0 2 i=1 6 i=2 1 i=3 k = 3 Sorted nums: 1 1 2 6 [1, 1, 2, 6] nums = [1,2,6,1] k = 3 (max operations) ALGORITHM STEPS 1 Sort Array Sort to find optimal window 2 Binary Search Search for max window size 3 Sliding Window Check if size is achievable 4 Calculate Cost Use median as target value Window Check (size=3): 1 1 2 6 Cost: |1-1|+|1-1|+|2-1| = 1 1 <= k(3), window valid! FINAL RESULT After operations: 1 1 1 6 same same 2 --> 1 skip Operations Used: nums[2]: 2 --> 1 (1 op) Total: 1 operation used Remaining: k-1 = 2 OUTPUT 3 Max frequency score = 3 [OK] Element 1 appears 3x Key Insight: Sort the array first, then use binary search on answer + sliding window to find the maximum window size where all elements can be made equal using at most k operations. The optimal target value within any window is the median (minimizes total distance). TutorialsPoint - Apply Operations to Maximize Frequency Score | Optimal Solution
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