Maximum Frequency of an Element After Performing Operations II - Problem

You are given an integer array nums and two integers k and numOperations.

You must perform an operation exactly numOperations times on nums, where in each operation you:

  • Select an index i that was not selected in any previous operations
  • Add an integer in the range [-k, k] to nums[i]

Return the maximum possible frequency of any element in nums after performing the operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,4,6], k = 3, numOperations = 2
Output: 3
💡 Note: Choose target value 4. Modify nums[0]: 2→4 and nums[2]: 6→4. Result: [4,4,4] with frequency 3.
Example 2 — Limited Operations
$ Input: nums = [1,4,5], k = 1, numOperations = 2
Output: 3
💡 Note: Choose target value 4. Modify nums[0]: 1→4 and nums[2]: 5→4. Result: [4,4,4] with frequency 3.
Example 3 — No Operations Needed
$ Input: nums = [3,3,3], k = 1, numOperations = 1
Output: 3
💡 Note: All elements are already equal to 3. No operations needed, frequency is already 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 109
  • 0 ≤ numOperations ≤ nums.length

Visualization

Tap to expand
Maximum Frequency After OperationsInput Array:246k = 3, numOperations = 2Choose target = 4444Operations: 2→4 (cost |2-4|=2), 6→4 (cost |6-4|=2)Maximum Frequency: 3
Understanding the Visualization
1
Input
Array with k constraint and numOperations limit
2
Process
Choose target and apply operations optimally
3
Output
Maximum frequency achievable
Key Takeaway
🎯 Key Insight: Binary search the maximum frequency and greedily verify feasibility by assigning operations to closest elements
Asked in
Google 15 Meta 12 Microsoft 8
8.8K 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