AiTechWorlds
AiTechWorlds
Animate the 0/1 Knapsack 2D DP table maximizing value within a weight capacity, with synced code.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| — | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| item1 (w1,v1) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| item2 (w3,v4) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| item3 (w4,v5) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| item4 (w5,v7) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
def knapsack(wt, val, W):
n = len(wt)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(W + 1):
dp[i][w] = dp[i-1][w]
if wt[i-1] <= w:
dp[i][w] = max(dp[i][w], dp[i-1][w-wt[i-1]] + val[i-1])
return dp[n][W]The 0/1 Knapsack problem maximizes total value within a weight capacity, choosing whole items. The 2D table dp[i][w] is the best value using the first i items within capacity w.
| Time | O(n × W) |
| Space | O(n × W) |
The 0/1 Knapsack Visualizer animates the 2D dynamic programming solution that maximizes total value within a weight capacity, choosing whole items. dp[i][w] is the best value using the first i items within capacity w, computed as max of skipping or taking item i. It runs in O(n × W) time and space.
Press Play
Watch the 2D table fill row by row as each item is considered.
Step through
Use Step Forward/Back or the timeline to see the take-vs-skip decision per cell.
Read the code
View the Knapsack DP in C++, Java, Python, or JavaScript and copy it.
100% Private — No Server Required
All processing happens directly in your browser. No data is uploaded, stored, or transmitted to any server.
Last reviewed on June 14, 2026 by the AiTechWorlds Tools Team. All processing runs locally in your browser.