Unbounded Fractional Knapsack | Function to return the maximum required value ; maxratio will store the maximum value to weight ratio we can have for any item and maxindex will store the index of that element ; Find the maximum ratio ; The item with the maximum value to weight ratio will be put into the knapsack repeatedly until full ; Driver code
function knapSack ( W , wt , val , n ) { var maxratio = - 1000000000 ; var maxindex = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( parseInt ( val [ i ] / wt [ i ] ) > maxratio ) { maxratio = ( val [ i ] / wt [ i ] ) ; maxindex = i ; } } return ( W * maxratio ) ; } var val = [ 14 , 27 , 44 , 19 ] ; var wt = [ 6 , 7 , 9 , 8 ] ; var n = val . length ; var W = 50 ; document . write ( knapSack ( W , wt , val , n ) . toFixed ( 3 ) ) ;