LC 3347. 执行操作后元素的最高频率 II
这题的关键在于选出可能的特征值出来,大约有三种: a) nums b) nums + k c) nums - k.
选出来可能的特征值之后,使用双指针的办法去寻找这些特征值可能覆盖的范围就行。
class Solution:
def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
from collections import Counter
cnt = Counter(nums)
tmp = sorted(nums)
cand = sorted(set([x - k for x in nums] + [x + k for x in nums] + nums))
# print(cand)
n = len(nums)
i, j = 0, 0
ans = 0
for c in cand:
while i < n and tmp[i] + k < c:
i += 1
while j < n and tmp[j] - k <= c:
j += 1
sz = min(numOperations, j - i - cnt[c]) + cnt[c]
# print(c, sz)
ans = max(ans, sz)
return ans