Given list of N items where each item has some [weight, value] associated with it, put the items into a knapsack of capacity W to maximize the sum of values associated with the items. Repetition of items is allowed.
This algorithm recursively explores all possible combinations of items, considering the weight constraint at each step, to find the selection that yields the maximum total profit. At each step, compare and take the maximum profit achievable from the two choices:
def pick(ls, w): if len(ls) <= 0 or w <= 0: return 0 take = 0 if ls[0][1] <= w: take = ls[0][0] + pick(ls, w - ls[0][1]); skip = pick(ls[1:], w) return max(take, skip) ls = [[10, 1], [40, 3], [50, 4], [70, 5]] W = 8 print(pick(ls, W))
function pick(list, w) { if (list.length <= 0 || w <= 0) { return 0; } let take = 0; if (list[0][1] <= w) { take = list[0][0] + pick(list, w - list[0][1]); } let skip = pick(list.slice(1), w); return Math.max(take, skip); } const list = [[10, 1], [40, 3], [50, 4], [70, 5]]; const W = 8; console.log(pick(list, W));