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: 2
💡 Note: Choose target value 4. Only nums[2] can be modified: 5→4 (since |1-4|=3 > k=1). Result: [1,4,4] with frequency 2.
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 Operations INPUT Array nums: 2 i=0 4 i=1 6 i=2 k = 3 ops = 2 Number Line with Ranges: 2 4 6 Each can move +/-3 Ranges: [-1,5], [1,7], [3,9] ALGORITHM (Greedy) 1 Find Overlaps Calculate reachable ranges [num-k, num+k] for each 2 Target Selection Find target value where most elements overlap 3 Count Coverage At target=5: all 3 elements can reach (within k=3) 4 Apply Operations Use 2 ops to move 2 and 6 One element already at 4 Target Analysis: 2 + 3 = 5 (within k) 4 + 1 = 5 (within k) 6 - 1 = 5 (within k) All 3 can reach 5! FINAL RESULT After 2 Operations: Original: [2, 4, 6] 2 --> 5 (+3) 4 --> 5 (+1) 6 --> 6 (no op) Result Array: 5 5 6 Maximum Frequency 3 OK - All 3 elements can reach value 5 Key Insight: The greedy approach finds the target value where maximum elements can converge within their reachable ranges. Each element nums[i] can reach any value in [nums[i]-k, nums[i]+k]. We find where these ranges overlap most, then use available operations to maximize frequency at that target. Here, target=5 allows all 3 elements to converge. TutorialsPoint - Maximum Frequency of an Element After Performing Operations II | Greedy Approach
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