Apply Operations to Maximize Frequency Score Problem
Description
LeetCode Problem 2968.
You are given a 0-indexed integer array nums and an integer k.
You can perform the following operation on the array at most k times:
- Choose any index
ifrom the array and increase or decreasenums[i]by1.
The score of the final array is the frequency of the most frequent element in the array.
Return the maximum score you can achieve.
The frequency of an element is the number of occurences of that element in the array.
Example 1:
Input: nums = [1,2,6,4], k = 3
Output: 3
Explanation: 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 2 is the most frequent in the final array so our score is 3.
It can be shown that we cannot achieve a better score.
Example 2:
Input: nums = [1,4,4,2,4], k = 0
Output: 3
Explanation: We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^90 <= k <= 10^14
Solution
Approach: Sorting + Prefix Sum + Binary Search
Sort nums. The elements that end up equal are best taken as a contiguous window of the sorted array, and the cheapest value to move them all to is the window's median.
If a frequency x is reachable, any smaller frequency is too, so the answer can be binary searched. To test a length mid, slide a window of that length over the array. With the prefix sums s, the cost of making all elements equal to the median m of window [i, j) is the amount the left part must rise, (p - i) * m - (s[p] - s[i]), plus the amount the right part must fall, (s[j] - s[p]) - (j - p) * m, where p is the median index. If some window costs at most k, mid is feasible.
The time complexity is O(n log n) and the space complexity is O(n), where n is the length of nums.
from itertools import accumulate
class Solution:
def maxFrequencyScore(self, nums: List[int], k: int) -> int:
nums.sort()
s = list(accumulate(nums, initial=0))
n = len(nums)
l, r = 0, n
while l < r:
mid = (l + r + 1) >> 1
ok = False
for i in range(n - mid + 1):
j = i + mid
x = nums[(i + j) // 2]
left = ((i + j) // 2 - i) * x - (s[(i + j) // 2] - s[i])
right = (s[j] - s[(i + j) // 2]) - ((j - (i + j) // 2) * x)
if left + right <= k:
ok = True
break
if ok:
l = mid
else:
r = mid - 1
return l