When I submitted the below code, it got failed for one test case.
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
left,right = 1,max(piles)
while left<=right:
mid = (left+right)//2
time = self.reqtime(piles,mid)
if time==h:
return mid
elif time<h:
right = mid-1
else:
left = mid+1
return left
def reqtime(self,arr,hourly):
total = 0
for i in arr:
total += -(-i//hourly)
return total
WRONG ANSWER 125 / 126 testcases passed
piles = [1,1,1,999999999]
h = 10
Output : 156250000
Expected : 142857143
But when I removed the code if time==h : return mid
and replaced it with if time<=h : right=mid-1
in the below code, it worked fine!
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
left,right = 1,max(piles)
while left<=right:
mid = (left+right)//2
time = self.reqtime(piles,mid)
if time<=h:
right = mid-1
else:
left = mid+1
return left
def reqtime(self,arr,hourly):
total = 0
for i in arr:
total += -(-i//hourly)
return total
Can someone explain why the first one doesn’t work? Because if time==h (h = maximum number of hours we have) , it means already k is the best case… If we increase the value of k , it will not be minimised. And if we decrease the value of k, it will cross the ‘h’ threshold.