forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apply-operations-to-maximize-frequency-score.py
76 lines (70 loc) · 2.07 KB
/
apply-operations-to-maximize-frequency-score.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Time: O(nlogn)
# Space: O(1)
# sort, two pointers, sliding window
class Solution(object):
def maxFrequencyScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
result = left = curr = 0
for right in xrange(len(nums)):
# "-+ " => "-0+ "
# "-0+ " => "--++"
curr += nums[right]-nums[(left+right)//2]
if not curr <= k:
# "--++" => " -0+"
# " -0+" => " -+"
curr -= nums[((left+1)+right)//2]-nums[left]
left += 1
return right-left+1
# Time: O(nlogn)
# Space: O(1)
# sort, two pointers, sliding window
class Solution2(object):
def maxFrequencyScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
result = left = curr = 0
for right in xrange(len(nums)):
# "-+ " => "-0+ "
# "-0+ " => "--++"
curr += nums[right]-nums[(left+right)//2]
while not curr <= k:
# "--++" => " -0+"
# " -0+" => " -+"
curr -= nums[((left+1)+right)//2]-nums[left]
left += 1
result = max(result, right-left+1)
return result
# Time: O(nlogn)
# Space: O(n)
# sort, prefix sum, binary search
class Solution3(object):
def maxFrequencyScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def check(l):
# "-+ " or "-0+"
return any((prefix[i+l]-prefix[i+(l+1)//2])-(prefix[i+l//2]-prefix[i]) <= k for i in xrange(len(nums)-l+1))
nums.sort()
prefix = [0]*(len(nums)+1)
for i, x in enumerate(nums):
prefix[i+1] = prefix[i]+x
left, right = 1, len(nums)
while left <= right:
mid = left+(right-left)//2
if not check(mid):
right = mid-1
else:
left = mid+1
return right