-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-frequency-of-an-element-after-performing-operations-i.py
62 lines (55 loc) · 1.74 KB
/
maximum-frequency-of-an-element-after-performing-operations-i.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Time: O(nlogn)
# Space: O(n)
import collections
# sort, freq table, two pointers, sliding window
class Solution(object):
def maxFrequency(self, nums, k, numOperations):
"""
:type nums: List[int]
:type k: int
:type numOperations: int
:rtype: int
"""
nums.sort()
result = 0
left, right = 0, -1
cnt = collections.defaultdict(int)
for i in xrange(len(nums)):
while right+1 < len(nums) and nums[right+1]-nums[i] <= k:
cnt[nums[right+1]] += 1
right += 1
while nums[i]-nums[left] > k:
cnt[nums[left]] -= 1
left += 1
result = max(result, cnt[nums[i]]+min((right-left+1)-cnt[nums[i]], numOperations))
left = 0
for right in xrange(len(nums)):
while nums[left]+k < nums[right]-k:
left += 1
result = max(result, min(right-left+1, numOperations))
return result
# Time: O(nlogn)
# Space: O(n)
import collections
# sort, freq table, difference array, line sweep
class Solution2(object):
def maxFrequency(self, nums, k, numOperations):
"""
:type nums: List[int]
:type k: int
:type numOperations: int
:rtype: int
"""
cnt = collections.defaultdict(int) # defaultdict is much faster than Counter
for x in nums:
cnt[x] += 1
diff = defaultdict(int)
for x in nums:
diff[x] += 0
diff[x-k] += 1
diff[x+k+1] -= 1
result = curr = 0
for x, c in sorted(diff.iteritems()):
curr += c
result = max(result, cnt[x]+min(curr-cnt[x], numOperations))
return result