Extended Knapsack Problem | To store the dp values ; for each element given ; For each possible weight value ; For each case where the total elements are less than the constraint ; To ensure that we dont go out of the array ; Driver Code
var dp = Array . from ( Array ( 100 ) , ( ) => Array ( 100 ) ) ; for ( var i = 0 ; i < 100 ; i ++ ) for ( var j = 0 ; j < 100 ; j ++ ) dp [ i ] [ j ] = new Array ( 100 ) . fill ( 0 ) ; function maxProfit ( profit , weight , n , max_W , max_E ) { for ( var i = 1 ; i <= n ; i ++ ) { for ( var j = 1 ; j <= max_W ; j ++ ) { for ( var k = 1 ; k <= max_E ; k ++ ) { if ( j >= weight [ i - 1 ] ) { dp [ i ] [ j ] [ k ] = Math . max ( dp [ i - 1 ] [ j ] [ k ] , dp [ i - 1 ] [ j - weight [ i - 1 ] ] [ k - 1 ] + profit [ i - 1 ] ) ; } else { dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j ] [ k ] ; } } } } return dp [ n ] [ max_W ] [ max_E ] ; } var n = 5 ; var profit = [ 2 , 7 , 1 , 5 , 3 ] ; var weight = [ 2 , 5 , 2 , 3 , 4 ] ; var max_weight = 8 ; var max_element = 2 ; document . write ( maxProfit ( profit , weight , n , max_weight , max_element ) + " " ) ;