Skip to content

Commit 34a919a

Browse files
committed
Time: 602 ms (58.72%), Space: 32.3 MB (79.07%) - LeetHub
1 parent 7b3332a commit 34a919a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# time complexity: O(max(nlogn, klogn))
2+
# space complexity: O(n)
3+
from bisect import bisect_left, bisect_right
4+
from typing import List
5+
6+
7+
class Solution:
8+
def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
9+
nums.sort()
10+
result = 0
11+
numCount = {}
12+
lastNumIdx = 0
13+
for i in range(len(nums)):
14+
if nums[i] != nums[lastNumIdx]:
15+
numCount[nums[lastNumIdx]] = i - lastNumIdx
16+
result = max(result, i - lastNumIdx)
17+
lastNumIdx = i
18+
19+
numCount[nums[lastNumIdx]] = len(nums) - lastNumIdx
20+
result = max(result, len(nums) - lastNumIdx)
21+
22+
for i in range(nums[0], nums[-1] + 1):
23+
left = bisect_left(nums, i - k)
24+
right = bisect_right(nums, i + k) - 1
25+
if i in numCount:
26+
temp = min(right - left + 1, numCount[i] + numOperations)
27+
else:
28+
temp = min(right - left + 1, numOperations)
29+
result = max(result, temp)
30+
31+
return result
32+
33+
34+
nums = [1, 4, 5]
35+
k = 2
36+
numOperations = 2
37+
print(Solution().maxFrequency(nums, k, numOperations))
38+
nums = [5, 16, 20, 20, 20, 24, 24]
39+
k = 5
40+
numOperations = 4
41+
print(Solution().maxFrequency(nums, k, numOperations))
42+
nums = [2, 70, 73]
43+
k = 39
44+
numOperations = 2
45+
print(Solution().maxFrequency(nums, k, numOperations))

0 commit comments

Comments
 (0)