Value to be subtracted from array elements to make sum of all elements equals K | Function to return the amount of wood collected if the cut is made at height m ; Function that returns Height at which cut should be made ; Sort the heights of the trees ; The minimum and the maximum cut that can be made ; Binary search to find the answer ; The amount of wood collected when cut is made at the mid ; If the current collected wood is equal to the required amount ; If it is more than the required amount then the cut needs to be made at a height higher than the current height ; Else made the cut at a lower height ; Driver code
function woodCollected ( height , n , m ) { let sum = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( height [ i ] - m <= 0 ) break ; sum += ( height [ i ] - m ) ; } return sum ; } function collectKWood ( height , n , k ) { height . sort ( ( a , b ) => a - b ) ; let low = 0 , high = height [ n - 1 ] ; while ( low <= high ) { let mid = low + ( ( high - low ) / 2 ) ; let collected = woodCollected ( height , n , mid ) ; if ( collected == k ) return mid ; if ( collected > k ) low = mid + 1 ; else high = mid - 1 ; } return - 1 ; } let height = [ 1 , 2 , 1 , 2 ] ; let n = height . length ; let k = 2 ; document . write ( collectKWood ( height , n , k ) ) ;