Maximum Frequency of an Element After Performing Operations I Problem
Description
LeetCode Problem 3346.
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]. nums becomes [1, 4, 5].
- Adding -1 to nums[2]. nums becomes [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 <= 10^51 <= nums[i] <= 10^50 <= k <= 10^50 <= numOperations <= nums.length
Solution
Approach: Difference array over the target value
Every element x can become any value in [x - k, x + k], but each operation changes a different index, and an element can only help a target v if |x - v| <= k. For a target v, let s be the number of elements that can reach v (those whose interval covers v) and cnt[v] the number already equal to v. Those equal to v need no operation, so the best frequency is cnt[v] + min(s - cnt[v], numOperations), which is min(s, cnt[v] + numOperations).
Only values where the coverage count can change need to be checked: each x itself (a target already in the array), x - k where an interval starts, and the end x + k + 1 where an interval stops. Store +1 at x - k, -1 at x + k + 1 and 0 at x in a map, sort its keys, take a running sum as s, and keep the largest value of the formula.
Complexity: O(n log n) time and O(n) space.
from collections import defaultdict
class Solution:
def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
cnt = defaultdict(int)
d = defaultdict(int)
for x in nums:
cnt[x] += 1
d[x] += 0
d[x - k] += 1
d[x + k + 1] -= 1
ans = s = 0
for x, t in sorted(d.items()):
s += t
ans = max(ans, min(s, cnt[x] + numOperations))
return ans