-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-time-to-repair-cars.py
52 lines (44 loc) · 1.32 KB
/
minimum-time-to-repair-cars.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
# Time: O(mx * log(mn * c^2)) = O(mx * (logc + log(mn))), c = cars, mx = max(ranks), mn = min(ranks)
# Space: O(mx)
import collections
# freq table, binary search
class Solution(object):
def repairCars(self, ranks, cars):
"""
:type ranks: List[int]
:type cars: int
:rtype: int
"""
def check(x):
return sum(int((x//k)**0.5)*v for k, v in cnt.iteritems()) >= cars
cnt = collections.Counter(ranks)
left, right = 1, min(cnt.iterkeys())*cars**2
while left <= right:
mid = left+(right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
# Time: O(c * log(mx)), c = cars, mx = max(ranks)
# Space: O(mx)
import collections
import heapq
# freq table, heap, simulation
class Solution2(object):
def repairCars(self, ranks, cars):
"""
:type ranks: List[int]
:type cars: int
:rtype: int
"""
cnt = collections.Counter(ranks)
min_heap = [(r*1**2, 1) for r in cnt.iterkeys()]
heapq.heapify(min_heap)
while cars > 0:
t, k = heapq.heappop(min_heap)
r = t//k**2
cars -= cnt[r]
k += 1
heapq.heappush(min_heap, (r*k**2, k))
return t