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.

Video lesson · Chapter 1 of 8

The field kit

0:00 / 6:13

0/1 knapsack in 75 seconds

1:25Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Take or leave each item. Leave it: dp[i - 1][w]. Take it if it fits: value + dp[i - 1][w - weight]

Understand it

Start here

The problem: a bag with a weight limit

You have nn items, item ii with weight wiw_i and value viv_i, and a bag that holds at most WW. Choose items to maximise the total value without going over WW. Each item is taken whole or left behind: 0 or 1, never half a tent and never two of the same item. The camping trip below has capacity 7 and the best load is worth 9.

The camping trip, capacity 7

ItemWeightValueValue per kgIn the best load?
Water bottle111.00no
Sleeping bag341.33yes
Tent451.25yes
Camping stove571.40no
Sleeping bag and tent: weight 3+4=73 + 4 = 7, value 4+5=94 + 5 = 9. The stove has the best value per kilo and is still left at home.

What this topic builds on

  • DP core

    State, recurrence, base case, fill order. Recapped in Dynamic programming: the core idea; here the state has two numbers.

  • Subsets

    Every load is a subset of the items, 2n2^n of them. Subsets lists them all; knapsack picks the best one without listing.

  • Take or skip

    The same binary choice as House robber, with a capacity that shrinks when you take.

Why simple rules fail

Greedy by value per kilo

The natural shortcut: sort by vi/wiv_i / w_i and pack the best ratios first. On the camping trip that packs the stove (1.40, 5 kg), finds that the bag (3 kg) and tent (4 kg) no longer fit in the 2 kg left, adds the bottle, and stops at 8. The bag and tent together give 9. Taking the stove early wasted room that nothing else could fill.

Fractional knapsack: greedy works

  • Items can be cut, like gold dust or bandwidth.
  • Take the best ratios whole, then a fraction of the next one.
  • Camping trip: stove plus 2/3 of the bag, 7+83≈9.677 + \tfrac{8}{3} \approx 9.67.
  • O(nlog⁡n)O(n \log n) for the sort.

0/1 knapsack: greedy fails

  • Items are whole: a gap left by a big item may stay empty.
  • Camping trip: greedy 8, best 9.
  • Capacity 50 with (10, 60), (20, 100), (30, 120): greedy 160, best 220.
  • Needs the DP table (or search).

The fractional optimum is an upper bound

OPT0/1  ≤  OPTfrac=∑wholevi+W−∑wholewiwk vk\text{OPT}_{0/1} \;\le\; \text{OPT}_{\text{frac}} = \sum_{\text{whole}} v_i + \frac{W - \sum_{\text{whole}} w_i}{w_k}\, v_k
Allowing cuts can only help, so the greedy fractional value (9.67 here) bounds the 0/1 answer (9). Branch and bound solvers use exactly this bound to prune.

Brute force

The take-or-skip tree

Define f(i,c)f(i, c) as the best value from the first $i$ items with $c$ units of room. For item ii: leave it and the answer is f(i−1,c)f(i-1, c); take it (only if wi≤cw_i \le c) and the answer is vi+f(i−1,c−wi)v_i + f(i-1, c - w_i). Below, three day-hike items: snacks (1, 2), first aid (2, 5), camera (2, 4), capacity 4.

Calls made by f(3, 4)

Leaves are omitted. Packing the camera and leaving first aid, or the reverse, both leave 2 units for the snacks: different paths, the same state (1,2)(1, 2).
Python
def knapsack_brute(weights, values, W):    def best(i, cap):        if i == 0:            return 0                              # no items left        wt, val = weights[i - 1], values[i - 1]        skip = best(i - 1, cap)                   # leave item i        if wt > cap:            return skip                           # does not fit        return max(skip, val + best(i - 1, cap - wt))    return best(len(weights), W)print(knapsack_brute([1, 2, 2], [2, 5, 4], 4))              # 9print(knapsack_brute([1, 3, 4, 5], [1, 4, 5, 7], 7))        # 9
The recurrence as plain recursion. Correct and exponential.
Edit and run it in your browser

Paths against states

T(n)=2 T(n−1)+O(1)⏟two calls per item=O(2n)but#{(i,c)}=(n+1)(W+1)\underbrace{T(n) = 2\,T(n-1) + O(1)}_{\text{two calls per item}} = O(2^n) \qquad \text{but} \qquad \#\{(i, c)\} = (n+1)(W+1)
Each item doubles the paths, one leaf per subset. The pairs (i,c)(i, c) the recursion can ask about are far fewer whenever WW is moderate, so most of those calls are repeats.

Fix 1

Memoise on (i, cap)

One memoised call

Each pair reaches the bottom boxes once. On the three hike items that is 12 calls instead of 14; on real inputs it is the difference between 2n2^n and n⋅Wn \cdot W.
Python
def knapsack_memo(weights, values, W):    memo = {}    def best(i, cap):        if i == 0:            return 0        if (i, cap) in memo:            return memo[(i, cap)]        wt, val = weights[i - 1], values[i - 1]        res = best(i - 1, cap)        if wt <= cap:            res = max(res, val + best(i - 1, cap - wt))        memo[(i, cap)] = res        return res    return best(len(weights), W)print(knapsack_memo([1, 3, 4, 5], [1, 4, 5, 7], 7))           # 9print(knapsack_memo([2, 3, 4, 5, 3], [3, 5, 6, 8, 4], 10))    # 16
Top-down with a dictionary keyed on both parts of the state.
Edit and run it in your browser

Cost of the memoised version

(n+1)(W+1)⏟states×O(1)⏟work each=O(n⋅W) time and space\underbrace{(n+1)(W+1)}_{\text{states}} \times \underbrace{O(1)}_{\text{work each}} = O(n \cdot W) \text{ time and space}
Recursion depth is only nn, one frame per item. For 100 items and capacity 1,000: about 100,000 states instead of 21002^{100} subsets.

The recurrence

dp[i][w] = max(leave, take)

Best value from the first i items with room w

dp[i][w]={0i=0 or w=0dp[i−1][w]wi>wmax⁡(dp[i−1][w],  vi+dp[i−1][w−wi])wi≤w\text{dp}[i][w] = \begin{cases} 0 & i = 0 \text{ or } w = 0 \\ \text{dp}[i-1][w] & w_i > w \\ \max\big(\text{dp}[i-1][w],\; v_i + \text{dp}[i-1][w - w_i]\big) & w_i \le w \end{cases}
The answer is dp[n][W]\text{dp}[n][W]. Row ii reads only row i−1i - 1: straight up for leave, up and wiw_i columns left for take.

Filling one cell

Two candidates, one comparison, one stored number per cell.

Why it is right. Take the best load for the first ii items and room ww. Either it leaves item ii, and then it is a load for the first i−1i - 1 items within ww, worth at most dp[i-1][w]. Or it packs item ii, and the rest is a load for the first i−1i - 1 items within w−wiw - w_i, worth at most dp[i-1][w - w_i]. Both are reachable, so the best is their max: optimal substructure. Using row i−1i - 1 in the take option is what stops item ii being packed twice.

Fix 2

Fill the table: the camping trip

dp[i][w] for capacity 7

Items so farw=01234567
none00000000
+ bottle (1, 1)01111111
+ bag (3, 4)01145555
+ tent (4, 5)01145669
+ stove (5, 7)01145789
dp[2][4] = max(dp[1][4], 4 + dp[1][1]) = max(1, 5) = 5: bag and bottle. dp[3][7] = max(5, 5 + dp[2][3]) = 9: tent and bag. In the last row the stove gives 7 + dp[3][2] = 8 and loses to 9.
Python
def knapsack(weights, values, W):    n = len(weights)    dp = [[0] * (W + 1) for _ in range(n + 1)]    for i in range(1, n + 1):        wt, val = weights[i - 1], values[i - 1]        for w in range(W + 1):            dp[i][w] = dp[i - 1][w]                  # leave item i            if wt <= w:                dp[i][w] = max(dp[i][w], val + dp[i - 1][w - wt])    return dp[n][W]print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7))         # 9  camping tripprint(knapsack([1, 2, 2, 3], [2, 5, 4, 3], 5))         # 11 day hikeprint(knapsack([2, 3, 4, 5, 3], [3, 5, 6, 8, 4], 10))  # 16 mountain expedition
Bottom-up: O(n⋅W)O(n \cdot W) time and space, no recursion.
Edit and run it in your browser
The whole method
  1. 1Itemsweights, values, W
  2. 2Row 0all zeros
  3. 3Each cellmax(leave, take)
  4. 4Cornerdp[n][W] = 9
  5. 5Walk backbag + tent

Reconstruction

Which items were packed?

Walking up from the corner

Changed means taken, equal means left. One step per item: O(n)O(n) on top of the table.

The walk on the camping table

Rowwdp[i][w]dp[i-1][w]DecisionRoom after
4 stove799left7
3 tent795packed7 - 4 = 3
2 bag341packed3 - 3 = 0
1 bottle000left0
Load: sleeping bag and tent, 7 kg, value 9.
Python
def knapsack_items(weights, values, W):    n = len(weights)    dp = [[0] * (W + 1) for _ in range(n + 1)]    for i in range(1, n + 1):        wt, val = weights[i - 1], values[i - 1]        for w in range(W + 1):            dp[i][w] = dp[i - 1][w]            if wt <= w:                dp[i][w] = max(dp[i][w], val + dp[i - 1][w - wt])    picked, w = [], W    for i in range(n, 0, -1):        if dp[i][w] != dp[i - 1][w]:            picked.append(i - 1)            w -= weights[i - 1]    return dp[n][W], picked[::-1]names = ["bottle", "bag", "tent", "stove"]best, idx = knapsack_items([1, 3, 4, 5], [1, 4, 5, 7], 7)print(best, [names[k] for k in idx])     # 9 ['bag', 'tent']
The best value and one optimal list of items.
Edit and run it in your browser

Fix 3

One row, swept right to left

Row ii reads only row i−1i - 1, so keep one array dp of length W+1W + 1 and overwrite it item by item. The catch is the read dp[w - wt]: it must still hold the previous item's row. Sweep ww from WW down to wiw_i and every smaller index is untouched when you read it.

Python
def knapsack_1d(weights, values, W):    dp = [0] * (W + 1)    for wt, val in zip(weights, values):        for w in range(W, wt - 1, -1):        # right to left            dp[w] = max(dp[w], val + dp[w - wt])    return dp[W]def knapsack_forward(weights, values, W):     # WRONG for 0/1    dp = [0] * (W + 1)    for wt, val in zip(weights, values):        for w in range(wt, W + 1):            # left to right            dp[w] = max(dp[w], val + dp[w - wt])    return dp[W]print(knapsack_1d([1, 3, 4, 5], [1, 4, 5, 7], 7))        # 9print(knapsack_forward([1], [1], 7))                      # 7: one bottle packed 7 times
The version to write in an interview when only the value is needed: O(n⋅W)O(n \cdot W) time, O(W)O(W) space.
Edit and run it in your browser

Why the direction decides the problem

Same line of code, opposite loop direction, a different problem. The forward sweep is exactly the unbounded knapsack.

One row

  • O(W)O(W) space: 8 cells instead of 40 on the camping trip.
  • Shortest code, the usual interview answer.
  • Loop stops at w=wiw = w_i: smaller capacities keep their values.

Full 2D table

  • O(n⋅W)O(n \cdot W) space.
  • Easier to explain and to debug cell by cell.
  • But keep it when you must list the packed items.

Complexity

O(n·W): pseudo-polynomial

Time and space

T(n,W)=Θ((n+1)(W+1))=O(n⋅W),S=O(n⋅W)  →  O(W)T(n, W) = \Theta\big((n+1)(W+1)\big) = O(n \cdot W), \qquad S = O(n \cdot W) \;\to\; O(W)
One max per cell. With the single row, space depends only on the capacity.

Why it is not truly polynomial

b=⌈log⁡2(W+1)⌉ bits to write W  ⟹  n⋅W≈n⋅2bb = \lceil \log_2 (W+1) \rceil \text{ bits to write } W \;\Longrightarrow\; n \cdot W \approx n \cdot 2^{b}
The running time is polynomial in the value of WW but exponential in its length. Add ten bits to WW and the table grows 1,024 times. That is what pseudo-polynomial means, and why 0/1 knapsack stays NP-hard.

Every approach

ApproachTimeSpaceUse it when
Brute-force take or skipO(2n)O(2^n)O(n)O(n) stackn is tiny (about 20 or fewer)
Memo on (i, cap)O(n⋅W)O(n \cdot W)O(n⋅W)O(n \cdot W)Quick to write from the recurrence; touches only reachable states
2D tableO(n⋅W)O(n \cdot W)O(n⋅W)O(n \cdot W)You need the list of items
One row, right to leftO(n⋅W)O(n \cdot W)O(W)O(W)Only the best value is needed
Greedy by ratioO(nlog⁡n)O(n \log n)O(1)O(1)Only for fractional knapsack
If WW is huge but values are small, flip the table: index by value and store the least weight (O(n · total value)).

Variants

Subset sum, partition, target sum

ProblemItem weightCell holdsUpdate (right to left)
0/1 knapsackwiw_ibest valuedp[w] = max(dp[w], v + dp[w - wt])
Subset sum to Tthe numberreachable? True/Falseok[s] = ok[s] or ok[s - x]
Partition equal subset sumthe numberreachable?subset sum with T=S/2T = S/2; odd SS is False
Count subsets with sum Tthe numbernumber of waysways[s] += ways[s - x]
Target sum (+/- signs)the numbernumber of wayscount subsets to (S+T)/2(S + T)/2
Last stone weight IIthe numberreachable?largest reachable s≤S/2s \le S/2; answer S−2sS - 2s
Same loop, same direction; only the operation in the cell changes.

Target sum reduces to counting subsets

P−N=T,P+N=S  ⟹  P=S+T2P - N = T,\quad P + N = S \;\Longrightarrow\; P = \frac{S + T}{2}
Numbers with a plus sign form PP, the rest NN. If S+TS + T is odd or ∣T∣>S|T| > S there are no ways. For [1, 1, 1, 1, 1] and T=3T = 3: count subsets summing to 4, which is 5.
Python
def can_partition(nums):    total = sum(nums)    if total % 2:        return False    target = total // 2    ok = [True] + [False] * target    for x in nums:        for s in range(target, x - 1, -1):            ok[s] = ok[s] or ok[s - x]    return ok[target]def target_sum_ways(nums, target):    S = sum(nums)    if abs(target) > S or (S + target) % 2:        return 0    P = (S + target) // 2    ways = [1] + [0] * P    for x in nums:        for s in range(P, x - 1, -1):            ways[s] += ways[s - x]    return ways[P]print(can_partition([2, 3, 4, 5]), can_partition([1, 2, 3, 5]))   # True Falseprint(target_sum_ways([1, 1, 1, 1, 1], 3))                        # 5
Partition and target sum, both one-row knapsacks.
Edit and run it in your browser

Spotting the pattern

Every branch on the right is the same right-to-left loop with a different cell operation.

Recap

Key takeaways

Key points

  • dp[i][w] is the best value from the first i items with room w; the answer is dp[n][W].
  • Leave item i: dp[i-1][w]. Take it only if it fits: value + dp[i-1][w - weight]. Keep the max.
  • The take option reads row i-1, so each item is used at most once.
  • Greedy by value per kilo fails for 0/1 (camping trip: 8 vs 9) and is only right for fractional knapsack.
  • Brute force is O(2^n); memo on (i, cap) or the table is O(n·W), pseudo-polynomial in W.
  • Walk back from the corner: changed means packed (subtract its weight), equal means left.
  • One row swept right to left gives O(W) space; sweeping left to right solves the unbounded knapsack instead.
  • Subset sum, partition and target sum are the same loop with or, or with +=.

Sources