Minimum cost to fill given weight in a bag | Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Build the table val [ ] in bottom up manner and return the last entry from the table ; Driver code
function minCost ( cost , n ) { let dp = new Array ( n + 1 ) ; dp [ 0 ] = 0 ; for ( let i = 1 ; i <= n ; i ++ ) { let min_cost = Number . MAX_VALUE ; for ( let j = 0 ; j < i ; j ++ ) if ( j < n ) min_cost = Math . min ( min_cost , cost [ j ] + dp [ i - j - 1 ] ) ; dp [ i ] = min_cost ; } return dp [ n ] ; } let cost = [ 20 , 10 , 4 , 50 , 100 ] ; let W = cost . length ; document . write ( minCost ( cost , W ) ) ;