-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwoodcut.py
39 lines (29 loc) · 977 Bytes
/
woodcut.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
class woodCut_solution:
"""
@param L: Given n pieces of wood with length L[i]
@param k: An integer
return: The maximum length of the small pieces.
"""
def woodCut(self, L, k):
#binary search to find the candidate
if not L:
return 0
min_ = lmin = 1
max_ = lmax = max(L)
median = 0 #max length
count = 0
res = 0
#corner case: if k is too large (or inplausible)
if sum(L) < k:
return 0
while lmin <= lmax:
median = (lmin+lmax)/2
count = sum([l/median for l in L])
if count < k: #cut size is too big, find the cut size in the first half
lmax = median
elif median > res:
res = median
lmin = median
else:
return res
return 0