AlgoViz

0/1 knapsack

medium 22 min

Pack items with weights and values into a bag of capacity W to get the most value, each item taken whole or not at all.

0/1 knapsack: brute force, memo, table with items, one row, and the subset-sum family

Read it, run it, change a line and run it again.

Loading editor…

knapsack_1d is the one to write when only the value is asked. Keep the 2D table when you need the items; switch the cell operation to or / += for the subset-sum problems.