Maximum sum of values of N items in 0 | Function to find the maximum value ; base condition ; K elements already reduced to half of their weight ; Dont include item ; If weight of the item is less than or equal to the remaining weight then include the item ; Return the maximum of both cases ; If the weight reduction to half is possible ; Skip the item ; Include item with full weight if weight of the item is less than the remaining weight ; Include item with half weight if half weight of the item is less than the remaining weight ; Return the maximum of all 3 cases ; Driver code
function maximum ( value , weight , weight1 , flag , K , index ) { if ( index >= value . length ) { return 0 ; } if ( flag == K ) { var skip = maximum ( value , weight , weight1 , flag , K , index + 1 ) ; var full = 0 ; if ( weight [ index ] <= weight1 ) { full = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] , flag , K , index + 1 ) ; } return Math . max ( full , skip ) ; } else { var skip = maximum ( value , weight , weight1 , flag , K , index + 1 ) ; var full = 0 ; var half = 0 ; if ( weight [ index ] <= weight1 ) { full = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] , flag , K , index + 1 ) ; } if ( weight [ index ] / 2 <= weight1 ) { half = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] / 2 , flag , K , index + 1 ) ; } return Math . max ( full , Math . max ( skip , half ) ) ; } } var value = [ 17 , 20 , 10 , 15 ] ; var weight = [ 4 , 2 , 7 , 5 ] ; var K = 1 ; var W = 4 ; document . write ( maximum ( value , weight , W , 0 , K , 0 ) ) ;