Capacity To Ship Packages Within D Days | Function to check if the weights can be delivered in D days or not ; Stores the count of days required to ship all the weights if the maximum capacity is mx ; Traverse all the weights ; If total weight is more than the maximum capacity ; If days are more than D , then return false ; Return true for the days < D ; Function to find the least weight capacity of a boat to ship all the weights within D days ; Stores the total weights to be shipped ; Find the sum of weights ; Stores the maximum weight in the array that has to be shipped ; Store the ending value for the search space ; Store the required result ; Perform binary search ; Store the middle value ; If mid can be shipped , then update the result and end value of the search space ; Search for minimum value in the right part ; Print the result ; Driver Code
function isValid ( weight , n , D , mx ) { let st = 1 ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum += weight [ i ] ; if ( sum > mx ) { st ++ ; sum = weight [ i ] ; } if ( st > D ) return false ; } return true ; } function shipWithinDays ( weight , D , n ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) sum += weight [ i ] ; let s = weight [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { s = Math . max ( s , weight [ i ] ) ; } let e = sum ; let res = - 1 ; while ( s <= e ) { let mid = s + Math . floor ( ( e - s ) / 2 ) ; if ( isValid ( weight , n , D , mid ) ) { res = mid ; e = mid - 1 ; } else s = mid + 1 ; } document . write ( res ) ; } let weight = [ 9 , 8 , 10 ] ; let D = 3 ; let N = weight . length ; shipWithinDays ( weight , D , N ) ;