Maximum Frequency of an Element After Performing Operations I - Problem

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

You must perform an operation 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 = [1,4,5], k = 1, numOperations = 2
Output: 2
💡 Note: We can change nums[0] to 2 (add 1) and nums[1] to 2 (subtract 2). However, we can only do 2 operations, so we can change nums[0] to 2 and keep nums[1] as 4. But better: change nums[0] from 1 to 4 (add 3, but this exceeds k). Actually, change nums[0] from 1 to 2 and nums[1] from 4 to 2, but nums[1] needs to change by 2 which exceeds k=1. Best solution: target value 4, change nums[0] from 1 to 4 (not possible with k=1). Target value 5: change nums[1] from 4 to 5 and keep nums[2] as 5, giving frequency 2.
Example 2 — All Same Target
$ Input: nums = [2,2,2], k = 2, numOperations = 2
Output: 3
💡 Note: All elements are already the same value 2. We don't need any operations, but we can use up to 2 operations on different indices. Since all 3 elements can have the same value without any operations, the maximum frequency is 3.
Example 3 — Limited Operations
$ Input: nums = [1,1,1,1], k = 1, numOperations = 1
Output: 4
💡 Note: All elements are already 1. Even though we can only perform 1 operation, all 4 elements already have the same value, so the maximum frequency is 4.

Constraints

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

Visualization

Tap to expand
Maximum Frequency: Transform Elements Within RangeInput: nums=[1,4,5], k=1, numOperations=2145±1±1±1Try target = 5:too far4→5keep 5Output: Maximum frequency = 2Two elements can be made equal to 5 within 2 operations
Understanding the Visualization
1
Input
Array nums=[1,4,5], k=1, numOperations=2
2
Process
Try different target values and count reachable elements
3
Output
Maximum frequency achievable is 2
Key Takeaway
🎯 Key Insight: Try each array element and its k-shifted values as potential targets to find maximum achievable frequency
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
324 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