Maximum Frequency of an Element After Performing Operations II - Solution & Explanation
Problem Statement
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
ithat was not selected in any previous operations. - Add an integer in the range
[-k, k]tonums[i].
Return the maximum possible frequency of any element in nums after performing the operations.
Example 1:
Input: nums = [1,4,5], k = 1, numOperations = 2
Output: 2
Explanation:
We can achieve a maximum frequency of two by:
- Adding 0 to
nums[1], after whichnumsbecomes[1, 4, 5]. - Adding -1 to
nums[2], after whichnumsbecomes[1, 4, 4].
Example 2:
Input: nums = [5,11,20,20], k = 5, numOperations = 1
Output: 2
Explanation:
We can achieve a maximum frequency of two by:
- Adding 0 to
nums[1].
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1090 <= k <= 1090 <= numOperations <= nums.length
Approach Overview
Problem Overview: You are given an array where operations can adjust values within a certain range. The goal is to maximize the frequency of a single element after performing at most k operations. Each operation allows modifying values so that multiple elements can be aligned to the same target value.
The challenge is determining which value should become the target and how many surrounding elements can be transformed into it while staying within the allowed operation budget. Efficient solutions rely on sorting, range counting, and window-based cost tracking.
Approach 1: Sliding Window Technique (Sorting + Prefix Cost Tracking) (Time: O(n log n), Space: O(1))
Sort the array so values are processed in increasing order. Once sorted, treat each value as a potential target and expand a sliding window that represents elements you want to convert to this target. As the right pointer grows, compute the cost required to raise all elements in the window to match the current value. If the cost exceeds the allowed operations, shrink the window from the left.
The key insight: after sorting, the cheapest way to increase frequency is to raise smaller elements toward a larger target. Maintaining a running window lets you check feasibility in constant time per step. This approach combines sorting with a classic sliding window pattern to efficiently track the maximum achievable frequency.
Approach 2: Greedy with Frequency Count (Binary Search + Prefix Sum) (Time: O(n log n), Space: O(n))
This method focuses on evaluating each unique value as a potential target. After sorting the array, build prefix sums so the cost of converting a range can be computed instantly. For each index, use binary search to determine the farthest left boundary where the cost to convert all numbers to the current value does not exceed the allowed operations.
The prefix sums allow quick computation of the total increments required to raise a subarray to the target value. Greedy reasoning ensures that expanding toward smaller values gives the largest possible group. This approach blends prefix sum range calculations with binary search to efficiently test valid windows.
Recommended for interviews: The sliding window solution is typically expected. It demonstrates strong understanding of sorted array properties, two‑pointer window expansion, and incremental cost maintenance. A brute force approach would check every possible target and range, which quickly becomes quadratic. Showing that baseline reasoning helps, but implementing the optimized sliding window proves algorithmic maturity.
Approach 1: Sliding Window Technique
This approach leverages a sorted array and the sliding window approach to maximize the frequency of elements. The idea is to use the sliding window to keep track of a subarray where you can potentially make all elements equal by performing add operations within the given range [-k, k].
You maintain a window that only expands when the needed operations are within the limit specified by numOperations. This involves checking the operations needed to turn the smallest element in the window into the largest element and adjusting it as necessary to stretch the window.
The C code uses quick-sort to sort the array and then applies a sliding window to calculate the maximum frequency of any number that can be achieved by performing operations. The steps:
- Sort the array.
- Use a loop with two pointers
leftandrightto maintain the window. - Calculate operations needed to make all numbers in this window equal to the number at the
rightpointer index and adjust theleftpointer accordingly. - Continuously update the result with the maximum window size encountered.
Code
C
Python
Java
C#
JavaScript
Complexity
Time Complexity: O(n log n) due to sorting, where n is the number of elements in the array.
Space Complexity: O(1) because modification is done in place.
Approach 2: Greedy with Frequency Count
This approach focuses on efficiently maximizing the frequency using a greedy strategy with a series of modifications limited by numOperations. It involves selectively manipulating elements to bunch them toward an optimal frequency level after sorting the array.
The process aims to utilize available changes strategically for maximizing occurrences of a particular value obtained.
The C++ code example applies sorting followed by greedy decision making:
- First, sort the array.
- Utilize a slipping window by maximizing frequencies with allowable operation limitations calculated during traversal.
- The sliding window shrinks when current needed operations for uniformity exceed specified
k. - Use comparisons to update maximum frequency efficiently.
Code
C++
JavaScript
Complexity
Time Complexity: O(n log n) due to sort operation as largest part.
Space Complexity: O(1) as changes are internal within the input collection.
Approach 3: Difference Array
According to the problem description, for each element x in the array nums, we can change it to any integer within the range [x-k, x+k]. We want to perform operations on some elements in nums to maximize the frequency of a certain integer in the array.
The problem can be transformed into merging all elements in the interval [x-k, x+k] corresponding to each element x, and finding the integer that contains the most original elements in the merged intervals. This can be implemented using a difference array.
We use a dictionary d to record the difference array. For each element x, we perform the following operations on the difference array:
- Add
1at positionx-k, indicating that a new interval starts from this position. - Subtract
1at positionx+k+1, indicating that an interval ends from this position. - Add
0at positionx, ensuring that positionxexists in the difference array for subsequent calculations.
At the same time, we need to record the number of occurrences of each element in the original array, using a dictionary cnt to implement this.
Next, we perform prefix sum calculation on the difference array to get how many intervals cover each position. For each position x, we calculate the number of intervals covering it as s. Then we discuss by cases:
- If
xappears in the original array, operations onxitself are meaningless. Therefore, there ares - cnt[x]other elements that can be changed toxthrough operations, but at mostnumOperationsoperations can be performed. So the maximum frequency at this position iscnt[x] + min(s - cnt[x], numOperations). - If
xdoes not appear in the original array, then at mostnumOperationsoperations can be performed to change other elements tox. Therefore, the maximum frequency at this position ismin(s, numOperations).
Combining the above two cases, we can uniformly express it as min(s, cnt[x] + numOperations).
Finally, we traverse all positions, calculate the maximum frequency at each position, and take the maximum value among them as the answer.
The time complexity is O(n times log n) and the space complexity is O(n), where n is the length of the array nums.
Complexity Comparison
| Approach | Complexity |
|---|---|
| Sliding Window Technique | Time Complexity: O(n log n) due to sorting, where n is the number of elements in the array. Space Complexity: O(1) because modification is done in place. |
| Greedy with Frequency Count | Time Complexity: O(n log n) due to sort operation as largest part. Space Complexity: O(1) as changes are internal within the input collection. |
| Difference Array | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sliding Window Technique (Sorted Array) | O(n log n) | O(1) | Best general solution after sorting. Efficient for large arrays and common interview expectation. |
| Greedy with Prefix Sum + Binary Search | O(n log n) | O(n) | Useful when prefix sums are already available or when analyzing valid ranges via binary search. |
| Naive Range Checking (Conceptual Baseline) | O(n^2) | O(1) | Only helpful for understanding the brute force idea before optimizing. |
Video Solution
Maximum Frequency of an Element After Performing Operations II | Difference Array | Leetcode 3347 • codestorywithMIK • 12,293 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Maximum Frequency of an Element After Performing Operations II easy or hard?
Maximum Frequency of an Element After Performing Operations II Python/Java solution
How to solve Maximum Frequency of an Element After Performing Operations II in O(n)?
What is the best approach for Maximum Frequency of an Element After Performing Operations II?
Is Maximum Frequency of an Element After Performing Operations II asked at Google/Amazon/Meta?
What data structure is used in Maximum Frequency of an Element After Performing Operations II?
What is the time complexity of Maximum Frequency of an Element After Performing Operations II?
Ready to solve this problem?
Practice Maximum Frequency of an Element After Performing Operations II with our built-in code editor and test cases.
Practice on FleetCodeTable of Contents
Practice this problem
Open in Editor