Skip to content

Commit 6e055f7

Browse files
authored
Create minimum-time-to-eat-all-grains.py
1 parent 15edfc3 commit 6e055f7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Time: O(mlogm + nlogn + (m + n) * logr), r = 2*(max(max(hens), max(grains))-min(min(hens), min(grains))
2+
# Space: O(1)
3+
4+
# binary search, greedy
5+
class Solution(object):
6+
def minimumTime(self, hens, grains):
7+
"""
8+
:type hens: List[int]
9+
:type grains: List[int]
10+
:rtype: int
11+
"""
12+
def check(x):
13+
i = 0
14+
for h in hens:
15+
if h-grains[i] > x:
16+
return False
17+
elif h-grains[i] > 0:
18+
d = h-grains[i]
19+
c = max(x-2*d, (x-d)//2) # max(go left then right, go right then left)
20+
else:
21+
c = x
22+
while i < len(grains) and grains[i] <= h+c:
23+
i += 1
24+
if i == len(grains):
25+
return True
26+
return False
27+
28+
hens.sort()
29+
grains.sort()
30+
left, right = 0, 2*(max(grains[-1], hens[-1])-min(grains[0], hens[0]))
31+
while left <= right:
32+
mid = left+(right-left)//2
33+
if check(mid):
34+
right = mid-1
35+
else:
36+
left = mid+1
37+
return left
38+

0 commit comments

Comments
 (0)