Maximum length possible by cutting N given woods into at least K pieces | Function to check if it is possible to cut woods into K pieces of length len ; Stores count of pieces having length equal to K ; Traverse wood array ; Update count ; Function to find the maximum value of L ; Stores minimum possible of L ; Stores maximum possible value of L ; Apply binary search over the range [ left , right ] ; Stores mid value of left and right ; If it is possible to cut woods into K pieces having length of each piece equal to mid ; Update left ; Update right ; Driver Code
function isValid ( wood , N , len , K ) { var count = 0 ; for ( i = 0 ; i < N ; i ++ ) { count += parseInt ( wood [ i ] / len ) ; } return count >= K ; } function findMaxLen ( wood , N , K ) { var left = 1 ; var right = Math . max . apply ( Math , wood ) ; while ( left <= right ) { var mid = left + ( right - left ) / 2 ; if ( isValid ( wood , N , mid , K ) ) { left = mid + 1 ; } else { right = mid - 1 ; } } return right ; } var wood = [ 5 , 9 , 7 ] ; var N = wood . length ; var K = 4 ; document . write ( findMaxLen ( wood , N , K ) ) ;