Knapsack Problem (Dynamic Programming)
Items:
Weight → Item ↓ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
---|
How the Knapsack Problem Works
The Knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
The algorithm:
- Create a table where rows represent items and columns represent weights from 0 to the knapsack capacity
- Fill the table using bottom-up dynamic programming
- For each cell, decide whether to include the current item or not, based on which choice maximizes value
- The value in the bottom-right cell is the maximum achievable value
- Backtrack through the table to determine which items were selected
This dynamic programming approach solves the problem in O(nW) time complexity, where n is the number of items and W is the knapsack capacity.
function knapsack(W, wt, val, n):
K = 2D array of size (n+1) x (W+1)
for i from 0 to n:
for w from 0 to W:
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
visualize(K, i, w, wt, val)
return K[n][W]
function visualize(K, i, w, wt, val):
// Update UI to show:
// 1. The current state of the K array
// 2. Highlight the current cell being calculated
// 3. Show the weight and value of the current item
// 4. Indicate which case of the algorithm is being applied