forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-running-time-of-n-computers.py
45 lines (39 loc) · 1.1 KB
/
maximum-running-time-of-n-computers.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
# Time: O(nlogm)
# Space: O(1)
import heapq
# greedy
class Solution(object):
def maxRunTime(self, n, batteries):
"""
:type n: int
:type batteries: List[int]
:rtype: int
"""
total = sum(batteries)
for i in xrange(len(batteries)):
batteries[i] = -batteries[i] # max_heap
heapq.heapify(batteries)
while -batteries[0] > total//n:
n -= 1
total -= -heapq.heappop(batteries)
return total//n
# Time: O(nlogr), r is the range of possible minutes
# Space: O(1)
# binary search
class Solution2(object):
def maxRunTime(self, n, batteries):
"""
:type n: int
:type batteries: List[int]
:rtype: int
"""
def check(n, batteries, x):
return sum(min(b, x) for b in batteries) >= n*x
left, right = min(batteries), sum(batteries)//n
while left <= right:
mid = left + (right-left)//2
if not check(n, batteries, mid):
right = mid-1
else:
left = mid+1
return right