Choose maximum weight with given weight and value ratio | Python3 program to choose item with maximum sum of weight under given constraint ; base cases : if no item is remaining ; first make pair with last chosen item and difference between weight and values ; choose maximum value from following two 1 ) not selecting the current item and calling recursively 2 ) selection current item , including the weight and updating the difference before calling recursively ; method returns maximum sum of weight with K as ration of sum of weight and their values ; Driver code
INT_MIN = - 9999999999 NEW_LINE def maxWeightRec ( wt , val , K , mp , last , diff ) : NEW_LINE INDENT if last == - 1 : NEW_LINE INDENT if diff == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return INT_MIN NEW_LINE DEDENT DEDENT tmp = ( last , diff ) NEW_LINE if tmp in mp : NEW_LINE INDENT return mp [ tmp ] NEW_LINE DEDENT mp [ tmp ] = max ( maxWeightRec ( wt , val , K , mp , last - 1 , diff ) , wt [ last ] + maxWeightRec ( wt , val , K , mp , last - 1 , diff + wt [ last ] - val [ last ] * K ) ) NEW_LINE return mp [ tmp ] NEW_LINE DEDENT def maxWeight ( wt , val , K , N ) : NEW_LINE INDENT return maxWeightRec ( wt , val , K , { } , N - 1 , 0 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT wt = [ 4 , 8 , 9 ] NEW_LINE val = [ 2 , 4 , 6 ] NEW_LINE N = len ( wt ) NEW_LINE K = 2 NEW_LINE print ( maxWeight ( wt , val , K , N ) ) NEW_LINE DEDENT