Knapsack Problem Variants
Compare 0/1, unbounded, and fractional knapsack with dynamic programming solutions, loop-direction rules, memory estimates, and variant-specific examples.
0/1 knapsack allows each item once, unbounded knapsack allows repeats, and fractional knapsack allows partial items. This guide compares their recurrences and loop directions, shows one-dimensional and two-dimensional dynamic programming, and explains why O(nW) is pseudo-polynomial. It also includes a capacity check and examples that show where value-to-weight greedy selection fails.
Knapsack Problem Variants
Introduction
Given items with positive integer weights and values, choose a subset whose total weight does not exceed capacity W and whose total value is as large as possible. The examples here assume W is a nonnegative integer and that the weight and value arrays have the same length. A 0/1 item can be selected once, an unbounded item can be selected repeatedly, and a fractional item can be split. Those rules determine the recurrence and loop direction.
Variant comparison
The recurrence table uses 1-based item indices; the Python functions below use 0-based list indices.
| Variant | Item reuse | Recurrence for item i and capacity w |
Capacity loop | Typical time and space |
|---|---|---|---|---|
| 0/1 | At most once | dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i]] + value[i]) |
Descending for a 1D array | O(nW) time; O(W) space, or O(nW) to keep the full table |
| Unbounded | Any number of times | dp[i][w] = max(dp[i-1][w], dp[i][w-weight[i]] + value[i]) |
Ascending so the current item can be reused | O(nW) time and O(W) space |
| Fractional | Any fraction from 0 to 1 | Take items by descending value-to-weight ratio, using a fraction of the last item if needed | No capacity DP loop | O(n log n) time to sort; O(n) extra space if a sorted copy is used |
The O(nW) running time is pseudo-polynomial, not polynomial in the encoded input length: a binary representation of W uses only O(log W) bits, while the DP visits capacities up to W.
Check the capacity before allocating
The 1D implementations below allocate W + 1 entries. The reconstruction version allocates (n + 1) * (W + 1) entries. In a language such as Python, each list entry also has object and reference overhead, so the cell count is not the full byte count. Estimate the table size using the target runtime and your memory budget before allocating it. There is no single capacity threshold that is safe for every language or machine.
If the table does not fit, consider a sparse state representation when few weight sums are reachable, meet-in-the-middle for a modest number of items, or an approximation/optimization method whose guarantees fit the problem. These alternatives have their own trade-offs; a large W alone does not identify the right one.
When to use
Knapsack DP fits selection problems with a discrete resource limit. Examples include choosing cargo for a truck, projects for a fixed budget, or tasks for a limited time window.
When not to use it
- Items can be divided: Use the ratio-greedy fractional algorithm. Unbounded knapsack has whole-item choices and still needs an algorithm suited to those discrete decisions.
- The capacity table will not fit: Consider sparse DP, meet-in-the-middle, or an approximation method after checking its assumptions and guarantee.
- Decisions are continuous: A linear-programming formulation may fit better than integer-capacity DP.
DP state transitions
graph TD
A["dp[i][w] = max value using first i items with weight limit w"] --> B{"Item i taken?"}
B -->|No| C["dp[i-1][w]"]
B -->|Yes| D["dp[i-1][w-weight[i]] + value[i]"]
A2[Unbounded: unlimited copies] --> B2{"Item i taken?"}
B2 -->|No| C2["dp[i-1][w]"]
B2 -->|Yes| D2["dp[i][w-weight[i]] + value[i]"]
Implementation
The DP code assumes every weight is a positive integer and capacity is a nonnegative integer. Zero-weight items need separate handling: in unbounded knapsack, a positive-value zero-weight item makes the objective unbounded. The two-constraint example also expects nonnegative integer capacities.
0/1 knapsack
def knapsack_01(weights, values, capacity):
"""
0/1 knapsack: each item taken at most once.
Time: O(n * capacity), Space: O(capacity)
"""
n = len(weights)
# Space-optimized: only need previous row
dp = [0] * (capacity + 1)
for i in range(n):
# Traverse backwards to avoid using updated values
for w in range(capacity, weights[i] - 1, -1):
dp[w] = max(dp[w], dp[w - weights[i]] + values[i])
return dp[capacity]
Unbounded knapsack
def knapsack_unbounded(weights, values, capacity):
"""
Unbounded knapsack: unlimited copies of each item.
Time: O(n * capacity), Space: O(capacity)
"""
dp = [0] * (capacity + 1)
for w in range(capacity + 1):
for i in range(len(weights)):
if weights[i] <= w:
dp[w] = max(dp[w], dp[w - weights[i]] + values[i])
return dp[capacity]
0/1 knapsack with item tracking
def knapsack_with_reconstruction(weights, values, capacity):
"""
0/1 knapsack with item selection reconstruction.
"""
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
dp[i][w] = dp[i - 1][w]
if weights[i - 1] <= w:
dp[i][w] = max(dp[i][w], dp[i - 1][w - weights[i - 1]] + values[i - 1])
# Reconstruct solution
selected = []
w = capacity
for i in range(n, 0, -1):
if dp[i][w] != dp[i - 1][w]:
selected.append(i - 1)
w -= weights[i - 1]
return dp[n][capacity], selected
Multi-dimensional knapsack
def knapsack_2d(weights, costs, values, max_weight, max_cost):
"""
0/1 knapsack with two constraints (weight and cost).
Time: O(n * max_weight * max_cost)
"""
dp = [[0] * (max_cost + 1) for _ in range(max_weight + 1)]
for i in range(len(values)):
for w in range(max_weight, weights[i] - 1, -1):
for c in range(max_cost, costs[i] - 1, -1):
dp[w][c] = max(dp[w][c], dp[w - weights[i]][c - costs[i]] + values[i])
return dp[max_weight][max_cost]
Tests that separate the variants
With one item of weight 2 and value 3, capacity 4 allows one copy in 0/1 knapsack and two copies in unbounded knapsack. These assertions catch an accidental forward loop in the 0/1 implementation:
assert knapsack_01([2], [3], 4) == 3
assert knapsack_unbounded([2], [3], 4) == 6
Ratio-greedy is exact for fractional items, but it can miss the best whole-item combination. Here, ratios are 6, 5, and 4. Greedy takes the first two items for value 160; the 0/1 optimum takes the 20- and 30-weight items for value 220. Fractional knapsack can take two thirds of the last item and reaches 240:
def ratio_greedy_01(weights, values, capacity):
items = sorted(
zip(weights, values),
key=lambda item: item[1] / item[0],
reverse=True,
)
total = 0
remaining = capacity
for weight, value in items:
if weight <= remaining:
total += value
remaining -= weight
return total
def fractional_knapsack(weights, values, capacity):
items = sorted(
zip(weights, values),
key=lambda item: item[1] / item[0],
reverse=True,
)
total = 0.0
remaining = capacity
for weight, value in items:
if remaining == 0:
break
fraction = min(1.0, remaining / weight)
total += fraction * value
remaining -= fraction * weight
return total
weights = [10, 20, 30]
values = [60, 100, 120]
capacity = 50
assert knapsack_01(weights, values, capacity) == 220
assert ratio_greedy_01(weights, values, capacity) == 160
assert abs(fractional_knapsack(weights, values, capacity) - 240.0) < 1e-9
Common pitfalls
- Forgetting backward traversal in 0/1: A forward pass can reuse the current item and count it more than once.
- Mutable default arguments: Do not use
dp=[]ordp={}as a function default. - Confusing unbounded with 0/1: Unbounded DP moves forward so it can read a value updated for the same item.
- Confusing capacity with memory: Python integers do not overflow at a fixed machine width, but a dense table can still run out of memory. Estimate the number of cells before allocating it.
Failure scenarios
| Scenario | What Went Wrong | Lesson Learned |
|---|---|---|
| E-commerce inventory system | A dense table grew beyond the job’s memory budget | Estimate cell count first; sparse DP may help when few sums are reachable |
| Container loading optimization | Ratio-greedy chose a different set than the optimum | Compare the heuristic against an exact result when the gap matters |
| Portfolio selection with transaction costs | Simple knapsack ignored fixed costs per transaction | Add transaction cost as separate dimension or post-process to group small items |
| Job scheduling with deadlines | Treated as 0/1 but jobs had soft dependencies | Precedence constraints require DAG-based DP, not standard knapsack |
Complexity and trade-offs
| Variant | Time | Space | Use when |
|---|---|---|---|
| 0/1, full table | O(nW) |
O(nW) |
You need to reconstruct selected items from the table. |
| 0/1, one row | O(nW) |
O(W) |
You need the optimum value and W fits the memory budget. |
| Unbounded | O(nW) |
O(W) |
Items can be reused and W fits the memory budget. |
| Fractional | O(n log n) to sort |
O(n) for a sorted copy |
Items can be split and value scales linearly with weight. |
| Two-constraint 0/1 | O(nW C) |
O(W C) |
Both capacities are modest enough for a dense table. |
Approximation schemes can give provable error bounds, but their running time depends on the chosen algorithm and its accuracy parameter. A ratio-greedy heuristic for 0/1 knapsack has no general guarantee of finding the optimum. Avoid fixed capacity cutoffs: compare the estimated table size with the memory available to the job.
Quick recap checklist
- 0/1 knapsack: traverse backwards, use previous row only
- Unbounded: traverse forward, can use current row (infinite supply)
- State: dp[i][w] = max value using first i items with weight limit w
- Base case: dp[0][w] = 0 (no items) and dp[i][0] = 0 (no capacity)
- Time complexity is O(n × capacity), which is pseudo-polynomial.
Interview questions
Backward traversal keeps dp[w - weight[i]] at the value from the previous item row. A forward update would let the current item be counted again during the same pass.
A 1D 0/1 update reads dp[w - weight[i]] before the current item has changed it. Descending capacity preserves that previous-row value. This lets one array replace the full table when you only need the optimum value.
In fractional knapsack, value scales with the amount taken, so sorting by value-to-weight ratio gives an optimal solution. That choice can fail when items must be taken whole: the highest-ratio item may block a better combination. The decision version of 0/1 knapsack is NP-complete; its optimization version is NP-hard.
Multi-dimensional knapsack adds another resource limit, such as volume or cost. A state dp[w][v] can store the best value for each weight and volume budget. The transition checks both limits before adding an item, so time and space grow with both capacity dimensions: O(n × maxWeight × maxVolume) time and O(maxWeight × maxVolume) space for a one-layer table.
Split the items into two groups and enumerate each group's subsets, about O(2^(n/2)) per side. Sort one group's sums, then for each sum on the other side find the largest compatible sum that stays within capacity. This uses exponential time and memory, but can be useful when n is moderate and W is too large for capacity-indexed DP.
Bounded knapsack specifies how many copies of each item you can take (e.g., item i has quantity limit m[i]).
The state transition adds a third dimension: dp[i][w] = max(dp[i-1][w], dp[i-1][w - k*weight[i]] + k*value[i])
for k = 1 to min(m[i], w/weight[i]). A common optimization uses binary decomposition: split each item into
powers-of-two bundles (1, 2, 4, ..., remainder) and treat each bundle as a separate 0/1 item, reducing bounded to
O(n log max_quantity) items.
Subset sum asks whether some numbers add to a target. It reduces to a 0/1 knapsack decision problem by using each number as both its weight and value, setting capacity to the target, and asking whether the optimum reaches the target. The general knapsack optimization problem can also answer its decision form: compare the optimum with a requested value threshold.
The full table keeps the value for every item prefix and capacity, which makes backtracking straightforward. A one-row table is enough for the optimum value, but it discards those intermediate rows. Other reconstruction methods can use less memory, at the cost of extra bookkeeping or recomputation.
Base cases: dp[0][w] = 0 (zero items can produce zero value) and dp[i][0] = 0 (zero capacity
holds zero value). These anchor the recurrence. All other cells start at 0 because we're maximizing and the minimum
achievable value is 0 (no items selected). This gives a consistent starting point for the recurrence; the
problem's positive-weight assumption keeps capacity states in their usual order.
Define dp[i][v] as the minimum weight needed to reach value v using the first i items. For a 1D 0/1
update, traverse values downward so an item is used at most once. A sparse Pareto frontier is another option when
only a small number of value-weight pairs are non-dominated.
Tabulation fills states in an order that makes each smaller subproblem available before it is used. Memoization starts from the requested state and caches subproblems as recursion reaches them. Memoization may save work when few states are reachable, but it adds call and cache overhead. Compare the reachable-state count and memory use for the actual input.
The main risk is usually memory, not integer overflow. A sparse map can help when only a small set of weight sums is reachable. If every integer capacity up to W is reachable, it may not save space. Dividing weights by their greatest common divisor preserves the exact problem; arbitrary rounding does not. Otherwise consider meet-in-the-middle or an approximation scheme with a guarantee that suits the application.
Sorting by value-to-weight ratio is a quick heuristic, but it does not guarantee the best 0/1 solution. The example above returns 160 while the optimum is 220. It can still provide an initial candidate for a local search. For branch-and-bound, the fractional relaxation gives an upper bound on the value of a partial solution.
The standard problem assumes positive weights. Negative weights change the feasible-set definition, so shifting every weight by a constant is not generally equivalent: it also changes the total weight according to how many items are selected. State the intended constraints first, then derive a recurrence for that formulation instead of applying the usual capacity DP unchanged.
Branch and bound explores the item decision tree but prunes branches that cannot beat the current best solution. A fractional-knapsack relaxation gives an upper bound for a partial choice: fill the remaining capacity with whole items by ratio, then use a fraction of the next item. Sort by ratio, branch on including or excluding an item, and prune when the bound cannot beat the best complete solution. It can reduce search on some instances, but worst-case time remains exponential.
Multiple knapsack assigns each item to at most one of K bins, each with its own capacity. Combining the capacities into one is not equivalent because an item must fit in a specific bin. A DP that tracks every bin's remaining capacity grows quickly with K; integer programming or a problem-specific heuristic may be more practical. Any heuristic should be checked against small instances where an exact answer is available.
The capacity W takes only O(log W) bits to encode, but the DP visits O(W) capacity values for each item.
Its running time is polynomial in the numeric value of W, not in the number of bits used to write W. If the table
is too large, consider another formulation or an approximation scheme whose error bound fits the application.
Dynamic capacity arises in problems like budget cycles or cargo with refueling stops. Two approaches: (1) Expand
the state to include time/capacity dimension: dp[i][w][t] where t is the time step and capacity varies
deterministically (e.g., decays or resets); (2) Treat each time period as a separate knapsack subproblem and use
the solution as input for the next period. If capacity changes stochastically, use Markov decision process (MDP)
formulation with value iteration. The complexity grows multiplicatively with time steps.
A PTAS gives a requested approximation ratio in time polynomial in n for each fixed ε; its time may grow quickly as ε shrinks. An FPTAS is polynomial in both n and 1/ε. Knapsack FPTAS algorithms commonly scale values before running a DP, but the exact complexity depends on the specific algorithm and formulation. Check that bound before choosing it for a workload.
For a simple dependency where selecting B requires A, add the constraint x_B ≤ x_A to an integer
programming model, where each x is 0 or 1. Tree-shaped dependency variants can use specialized dynamic programs.
A plain knapsack recurrence does not enforce these relationships, so derive the state from the dependency rules
instead of combining items by default.
Further reading
- Dynamic Programming: Introduction: Core DP patterns used by knapsack.
- Greedy Algorithms: When greedy choices are exact, including fractional knapsack.
- MIT Knapsack Lecture Notes: Dynamic programming lecture material.
- Stanford CS161: More knapsack examples.
Conclusion
Start by checking whether an item can be reused or split. For 0/1 knapsack, update capacities backward; for unbounded knapsack, update forward. Fractional knapsack is the case where ratio-greedy is exact. Before running capacity-indexed DP, estimate the table size and compare it with the memory budget. For more DP patterns, see Dynamic Programming: Introduction.
Category
Related Posts
Memoization vs Tabulation: Two Faces of Dynamic Programming
Understand the two fundamental DP approaches—top-down with memoization and bottom-up with tabulation—plus hybrid techniques like the/m on the fly.
1D Dynamic Programming Problems: Classic Patterns
Learn to solve common 1D dynamic programming problems including climbing stairs, house robber, and coin change with optimized space solutions.
2D Dynamic Programming: Matrix Chain and Beyond
Master 2D DP problems with two state variables for string manipulation, matrix chain multiplication, and optimal game strategies.