Koko Eating Bananas | Python implementation for the above approach ; to get the ceil value ; in case of odd number ; in case of even number ; check if time is less than or equals to given hour ; as minimum speed of eating must be 1 ; Maximum speed of eating is the maximum bananas in given piles ; Check if the mid ( hours ) is valid ; If valid continue to search lower speed ; If cant finish bananas in given hours , then increase the speed ; Driver code
def check ( bananas , mid_val , H ) : NEW_LINE INDENT time = 0 ; NEW_LINE for i in range ( len ( bananas ) ) : NEW_LINE INDENT if ( bananas [ i ] % mid_val != 0 ) : NEW_LINE time += bananas [ i ] // mid_val + 1 ; NEW_LINE else : NEW_LINE time += bananas [ i ] // mid_val NEW_LINE DEDENT if ( time <= H ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def minEatingSpeed ( piles , H ) : NEW_LINE INDENT start = 1 ; NEW_LINE end = sorted ( piles . copy ( ) , reverse = True ) [ 0 ] NEW_LINE while ( start < end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE if ( check ( piles , mid , H ) == True ) : NEW_LINE end = mid ; NEW_LINE else : NEW_LINE start = mid + 1 ; NEW_LINE DEDENT return end ; NEW_LINE DEDENT piles = [ 30 , 11 , 23 , 4 , 20 ] ; NEW_LINE H = 6 ; NEW_LINE print ( minEatingSpeed ( piles , H ) ) ; NEW_LINE