Koko Eating Bananas | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < int > & bananas , int mid_val , int H ) { int time = 0 ; for ( int i = 0 ; i < bananas . size ( ) ; i ++ ) { if ( bananas [ i ] % mid_val != 0 ) { time += ( ( bananas [ i ] / mid_val ) + 1 ) ; } else { time += ( bananas [ i ] / mid_val ) ; } } if ( time <= H ) { return true ; } else { return false ; } } int minEatingSpeed ( vector < int > & piles , int H ) { int start = 1 ; int end = * max_element ( piles . begin ( ) , piles . end ( ) ) ; while ( start < end ) { int mid = start + ( end - start ) / 2 ; if ( ( check ( piles , mid , H ) ) == true ) { end = mid ; } else { start = mid + 1 ; } } return end ; } int main ( ) { vector < int > piles = { 30 , 11 , 23 , 4 , 20 } ; int H = 6 ; cout << minEatingSpeed ( piles , H ) ; return 0 ; }