Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Dynamic Programming

The Loaded Bag.

Watch the explainer

Don't memorize the knapsack DP — watch the table fill. You have a bag with a weight limit and items each worth something. For every item and every capacity, one question: take it or leave it? A grid remembers the best answer to every smaller version of the problem, so each cell is decided in one comparison — and a trace back reveals exactly which items made the cut.

take or leave · dp[i][w] · traceback · O(n·W)
ITEM

Each has a weight and a value. Take it whole, or not at all.

dp[i][w]

Best value using the first i items within capacity w.

THE CHOICE

max(leave = dp[i−1][w], take = value + dp[i−1][w−weight]).

TRACEBACK

Compare each cell to the one above to see if the item was taken.

knapsack.sim — weights [1,3,4], values [15,20,30], capacity 4
Ready

A DP table: rows are items, columns are capacities 0…4. Row 0 is “no items”, all zeros. Press Step to add one item per row — each cell takes the better of leaving or taking the item — then trace back the winners.

0
Best value
O(n·W)
Cost

Every subproblem, answered once

Trying every subset of items is O(2ⁿ) — hopeless past a handful. The DP trick is to notice that the best you can do with the first i items and capacity w only depends on the answers for i−1 items. So build a table of every (items, capacity) pair, fill it once from the top, and each cell reuses two cells above it. The last cell, dp[n][W], is the answer — and the path back through the table tells you the items.

01

Leave it

Skip the item: value is whatever you had with the previous items and the same capacity, dp[i−1][w].

02

Take it (if it fits)

Add its value and use the best of the rest with the leftover capacity: value + dp[i−1][w − weight].

03

Keep the max

dp[i][w] = max(leave, take). Fill the whole grid row by row — the answer is the bottom-right cell.

04

Trace back

From dp[n][W]: if a cell equals the one above, the item was left; if not, it was taken — drop its weight and keep going up.

Time
O(n·W)
Space
O(n·W)
Brute force
O(2ⁿ)
Class
NP-hard

This is “pseudo-polynomial”: the runtime depends on the numeric capacity W, not just the item count, so huge capacities are slow (the problem is NP-hard). You can shrink the space to a single row by filling capacities right-to-left. Cousins include unbounded knapsack (unlimited copies), subset sum, and coin change — all the same table with a tweaked recurrence.

The picture: the table and the way back

01234no items00000item 1 (1, 15)015151515item 2 (3, 20)015152035item 3 (4, 30)015152035traceback: leave item 3 · take item 2 · take item 1
The page’s instance, filled by code. Highlighted cells are the traceback from the corner. At (3, 4) the cell equals the one above it, so the weight-4 item was left. At (2, 4) it differs, so the weight-3 item was taken and the walk jumps to capacity 1. At (1, 1) it differs again: the weight-1 item was taken. Best value 35.

Worked example, step by step

Weights [1, 3, 4], values [15, 20, 30], capacity 4. Each row below is one cell dp[i][w]: leave is the cell directly above, take is the item’s value plus the cell above and weight to the left (blank when the item does not fit).

iwItem fits?LeaveTakedp[i][w]
10no0—0
11yes015 + dp[0][0] = 1515
14yes015 + dp[0][3] = 1515
21no15—15
22no15—15
23yes1520 + dp[1][0] = 2020
24yes1520 + dp[1][1] = 3535
31no15—15
32no15—15
33no20—20
34yes3530 + dp[2][0] = 3035

Read the highlighted rows: that is where taking beat leaving. Row 1 is easy: the weight-1 item fits from w = 1 and is worth 15. Row 2 shows the real decision at w = 3: the weight-3 item alone gives 20, which beats 15, so the table switches. At w = 4 it takes 20 plus dp[1][1] = 15, giving 35, which is exactly the “remember the best for the leftover room” step. Row 3 changes nothing: the weight-4 item would need all of the room, and 30 is less than 35, so the last row copies the one above. Per-weight value is no guide here (ratios 15, 6.7 and 7.5); a table cell compares whole outcomes, not ratios. The answer is dp[3][4] = 35, the grid is 3 × 4 cells of work standing in for 8 subsets.

Complexity and trade-offs

CaseTimeSpaceWhy
2-D tableO(n·W)O(n·W)One cell per (item, capacity), two lookups each. Keeps every row, so the traceback can recover the items.
One rolling rowO(n·W)O(W)Same work, one array, capacities filled right to left. The value survives; the item list does not.
Brute forceO(2ⁿ·n)O(n)Try every subset and add it up. Fine to n ≈ 20, hopeless past 40.
Meet in the middleO(n·2^(n/2))O(2^(n/2))Enumerate both halves, sort, and pair them. Wins when W is huge and n is about 40.
Greedy by value/weightO(n log n)O(1)Optimal only when items can be split. For 0/1 items it is wrong (see below).

The runtime depends on the number W, not on how many digits it takes to write, which is why the problem is NP-hard and still solved by a table: the algorithm is pseudo-polynomial. If W is 1,000 the table is tiny; if W is 10⁹ the table needs 10⁹ cells, and meet in the middle or branch and bound is the better tool. When only the value is needed, the single-row version cuts memory by a factor of n.

Common mistakes

  • Filling the single row left to right

    With one array, looping w upward lets an item be counted again within the same pass, which silently turns 0/1 into unbounded knapsack. On weights [1, 3, 4], values [15, 20, 30], capacity 4 it returns 60 (the weight-1 item four times) instead of 35. Loop w from W down to the item’s weight.

  • Skipping the “does it fit” test

    Reading dp[i-1][w - weight] when weight > w is a negative index. Python does not raise; it wraps to the end of the row. A single item of weight 3, value 10 and capacity 2 then returns 10 instead of 0, and the page’s instance returns 65 instead of 35.

  • Trusting the best ratio

    Weights [10, 20, 30], values [60, 100, 120], capacity 50: greedy by value per weight takes the first two for 160, but items 2 and 3 fill the bag exactly for 220. Greedy is the right answer only for the fractional version.

  • Reconstructing from the wrong comparison

    The traceback must compare dp[i][w] with dp[i-1][w] (same capacity, row above). Comparing with the left neighbour finds nothing, because capacity is not what changed. After a “take”, subtract the weight before moving up, or every later step reads the wrong column.

  • Using it when W is huge

    Capacities such as 10⁹ (money in cents, bytes, nanoseconds) make the table, not the item count, the cost: a 10⁹-cell row of 4-byte integers is 4 GB. Scale values down, switch to a value-indexed table, or use meet in the middle.

Where this shows up

  • Budgeted selection

    Choosing which features to build for a fixed sprint, which ads to run under a daily spend cap, or which files fit on a disc is the same “value per cost, one budget” structure. When the cost is an integer with a modest range, the table solves it exactly.

  • Subset sum and partition

    Setting every value equal to its weight turns it into subset sum. “Can this array be split into two equal-sum halves?” (the partition problem) asks whether dp[n][total/2] equals total/2, and is a standard interview application.

  • Cryptography history

    The Merkle–Hellman public-key scheme (1978) hid a trapdoor inside a knapsack problem. Shamir broke it in 1982, a useful lesson: NP-hard in general does not mean hard on the instances a scheme produces.

  • Variants worth knowing

    Unbounded knapsack and coin change allow repeats and fill the row left to right. Multi-dimensional knapsack (for example, bags limited by both weight and volume) adds a table axis, so cost grows with each limit.

SOLVE IT YOURSELF

Solve it: 0/1 knapsack

This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement knapsack(weights, values, capacity): pick a subset of items (each usable at most once) whose total weight fits the capacity, maximizing total value. Return that max value. Fill a DP table dp[c] = best value for capacity c — O(n × capacity).

HINTS — 4 IDEAS
  1. Let dp[c] be the best value achievable with a weight budget of c. Start it all zeros.
  2. For each item, decide: skip it (keep dp[c]) or take it (dp[c − weight] + value) — keep the larger.
  3. To use each item only once, sweep the capacity downward (from capacity to weight), so this item is not reused within the same pass.
  4. The answer is dp[capacity] after all items.
CPython · WebAssembly

Check yourself

1 · What does dp[i][w] represent?

Each cell caches the optimal value for a subproblem — the first i items and a capacity of w.

2 · How is each cell computed?

Take the better of skipping the item or taking it (if it fits) plus the best of the rest with the remaining capacity.

3 · During traceback, a cell equals the cell directly above it. That means:

Equal to the cell above means leaving the item was optimal, so it was not part of the chosen set — move straight up.

Questions

What is the difference from fractional knapsack?

Fractional knapsack lets you take part of an item, which makes a simple greedy (best value-per-weight first) optimal and O(n log n). The 0/1 version forbids fractions, breaks greedy, and needs the DP table.

How do you save memory?

Each row only depends on the previous row, so you can keep a single 1-D array of size W+1 and update it from high capacity down to low — O(W) space instead of O(n·W).

How does coin change relate?

Coin change is knapsack with unlimited copies of each coin and a different objective (fewest coins, or number of ways). Same table shape, the recurrence allows reusing the current row because items are unbounded.

Take it or leave it, one cell at a time.

Fill the grid once, read the answer off the corner, trace back the items. The DP workhorse.

▶  Watch it explained

Knapsack: Leave It or Take It, One Table

Finished this one? 0 / 99 Algorithms done
NextThe Longest Climb: Longest Increasing Subsequence Next on the “DP along one axis” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms