Problem Description
Given an integer array nums and two integers k and numOperations, you are allowed to perform exactly numOperations operations. In each operation, you select an index that has not been used before and add any integer from the range [-k, k] to nums[i]. The goal is to maximize the frequency (the count) of any element in nums after these operations.
Key Insights
- Each operation can adjust one element by at most k in either direction.
- An element already equal to the target value does not need an operation.
- For a candidate target value T, only those numbers that are already T or can be changed to T (i.e. those satisfying |nums[i] - T| ≤ k) are eligible.
- The maximum achievable frequency for T is: frequency(T) plus at most numOperations additional eligible numbers (i.e. those within [T - k, T + k] that are not already T).
- Using a frequency array and prefix sum over the value range allows computing the count of numbers in any interval quickly.
- Finally, iterate over candidate target values in the range of possible numbers to find the maximum achievable frequency.
Space and Time Complexity
Time Complexity: O(M) where M is the maximum possible value (up to 10^5), since we precompute frequency and prefix sums and then iterate over the candidate values. Space Complexity: O(M) for the frequency and prefix sum arrays.
Solution
We first count the frequency of every possible value in nums. Then, using a prefix sum array over this frequency array, we can quickly determine the number of elements whose values lie in any interval [T-k, T+k]. For each candidate target T (from 1 to maximum value), the eligible count is the number of elements in the range [T-k, T+k].
Since any element that is not already T but lies in this interval can be changed into T by using one operation (provided we have not exceeded numOperations), the maximum achievable frequency if we pick T as the target is:
frequency(T) + min(numOperations, (eligible count − frequency(T)))
We take the maximum value across all possible T. This approach uses frequency arrays, prefix sum techniques, and a linear scan over possible target values.