Input: nums =[1,2,6,4], k =3Output: 3Explanation: We can do the following operations on the array:- Choose i =0, and increase the value of nums[0] by 1. The resulting array is[2,2,6,4].- Choose i =3, and decrease the value of nums[3] by 1. The resulting array is[2,2,6,3].- Choose i =3, and decrease the value of nums[3] by 1. The resulting array is[2,2,6,2].The element 2is the most frequent in the final array so our score is3.It can be shown that we cannot achieve a better score.
Input: nums =[1,4,4,2,4], k =0Output: 3Explanation: We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is3.
The best value to make all elements in a window equal to (with minimal total absolute change) is the median of the window. After sorting the array, for any sliding window [l..r] the median index is med = (l + r + 1) / 2. When we add a new right element nums[r] the additional cost to make the window elements equal to the (possibly updated) median increases by nums[r] - nums[old_median]; when we remove the left element nums[l] the cost decreases by nums[old_median] - nums[l]. Using this incremental update with a sliding window and maintaining med lets us check feasibility against k in linear time.
Use a sliding window [l..r] and maintain med = (l + r + 1) / 2 (integer division). Maintain a running cost that equals the total operations required to make all elements in [l..r] equal to nums[med].
When extending the window with r++, increment cost by nums[r] - nums[old_med], then recompute med = (l + r + 1) / 2.
While cost > k, advance l and decrement cost by nums[old_med] - nums[l], updating med after each move.
Track maxFreq = max(maxFreq, r - l + 1) as the window expands.
This uses the median-based incremental update to avoid summing the whole window on every change.
classSolution {
public:int maxFrequencyScore(std::vector<int>& nums, longlong k) {
std::sort(nums.begin(), nums.end());
int n = nums.size();
int left =0;
int ans =1;
longlong cost =0;
int medianIdx =0;
for (int right =1; right < n; ++right) {
cost += (longlong)nums[right] - nums[medianIdx];
medianIdx = (left + right +1) /2;
while (cost > k) {
cost -= (longlong)nums[medianIdx] - nums[left];
left++;
medianIdx = (left + right +1) /2;
}
ans = std::max(ans, right - left +1);
}
return ans;
}
};