Koko Eating Bananas | Javascript 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
function check ( bananas , mid_val , H ) { let time = 0 ; for ( let i = 0 ; i < bananas . length ; i ++ ) { if ( bananas [ i ] % mid_val != 0 ) { time += Math . floor ( bananas [ i ] / mid_val ) + 1 ; } else { time += Math . floor ( bananas [ i ] / mid_val ) ; } } if ( time <= H ) { return true ; } else { return false ; } } function minEatingSpeed ( piles , H ) { let start = 1 ; let end = [ ... piles ] . sort ( ( a , b ) => b - a ) [ 0 ] ; while ( start < end ) { let mid = start + Math . floor ( ( end - start ) / 2 ) ; if ( check ( piles , mid , H ) == true ) { end = mid ; } else { start = mid + 1 ; } } return end ; } let piles = [ 30 , 11 , 23 , 4 , 20 ] ; let H = 6 ; document . write ( minEatingSpeed ( piles , H ) ) ;