Author: Hang Li (@flgkd)
Note: Titles marked with ⭐ highlight key concepts and important summaries.
This note studies the knapsack problem, one of the most classical problems in combinatorial optimization and integer programming.
This note is primarily based on Sun and Li's Integer Programming [1], together with standard references on knapsack problems [2,3].
The knapsack problem is important for at least three reasons:
- it is a standard model for resource allocation under capacity constraints;
- it is a central example in dynamic programming;
- it plays an important role in computational complexity theory.
A point that should be stated carefully is the following:
For the standard 0-1 knapsack problem with binary-encoded integer data, the decision version is NP-complete, while the optimization version is NP-hard [3].
So when people casually say that “the knapsack problem is NP-complete,” they are normally referring to the standard decision form, not the optimization problem itself.
This note mainly focuses on several standard variants:
- 0-1 knapsack;
- unbounded / complete knapsack;
- bounded knapsack;
- grouped knapsack.
Since the previous note already introduced the general idea of dynamic programming, this note will emphasize how those ideas are specialized to knapsack-type models.
For a review of dynamic programming, see:
For a review of complexity issues such as NP-completeness and pseudo-polynomial time, see:
In its most intuitive form, the knapsack problem asks:
Given a set of items, each with a weight (or volume) and a value, how should we choose items so that the total weight does not exceed the capacity of the knapsack and the total value is as large as possible?
This is a maximization problem under a capacity constraint.
The name comes from the physical interpretation of selecting the most valuable collection of items that can fit into a capacity-limited knapsack. Knapsack-type models and closely related subset-selection problems appear in resource allocation, combinatorial optimization, computational complexity, and applied mathematics [2,3]. They also appeared historically in public-key cryptographic constructions, notably the Merkle-Hellman trapdoor-knapsack scheme [4].
A standard 0-1 formulation is
subject to
Here:
-
$a_j$ is the weight / volume of item$j$ ; -
$c_j$ is the value / profit of item$j$ ; -
$B$ is the capacity of the knapsack; -
$x_j=1$ means item$j$ is selected, and$x_j=0$ means it is not selected.
The optimization form asks for the maximum achievable value.
The corresponding decision form asks:
Is there a feasible selection whose total weight is at most
$B$ and whose total value is at least some target value$V$ ?
This distinction is important in complexity theory:
- the decision version is NP-complete;
- the optimization version is NP-hard.
The knapsack problem is a very typical dynamic programming (DP) problem.
Its structure is suitable for DP because:
- we need to consider all feasible possibilities while still computing the true optimum;
- many subproblems repeat, so intermediate results should be stored;
- the problem can be decomposed into smaller subproblems through a state transition equation.
The key structural property is optimal substructure. This state-based recursive viewpoint is part of the classical dynamic-programming framework developed by Bellman [5].
In practice, for a dynamic-programming formulation, the most important tasks are:
- defining the state clearly;
- describing the optimal substructure;
- deriving the recurrence relation.
The classical knapsack dynamic program used throughout this note takes the capacity as a state index:
Therefore, the standard
This integer requirement comes from the state space, not from the objective values.
The item values
cause no difficulty, because the values are stored in the DP table rather than used as array indices.
The important distinction is:
The quantity used as the DP index must be discretely enumerable. In the classical capacity-indexed knapsack DP, that quantity is the weight / capacity.
The Python implementations in this note read integer inputs for simplicity, but mathematically the value coefficients may be real numbers.
The knapsack problem itself does not require integer weights. What changes is whether the classical capacity-indexed DP can be used directly.
There are several common cases.
If all weights and the capacity have a common finite precision, multiply them by a common scaling factor.
For example,
can be multiplied by
The ordinary integer-capacity DP can then be applied exactly.
More generally, rational weights can be multiplied by a common denominator.
However, scaling may make the capacity very large. If the original data have many decimal places, the scaled value
If the values
Define
For the 0-1 problem, initialize
and
For
For
The weights
After computing states for
This is a value-indexed dynamic program rather than a capacity-indexed one. Its running time is
If neither the weights nor the values admit a useful discrete scaling, one can no longer rely on the simple
Possible approaches include:
- maintaining only nondominated
$(\text{weight},\text{value})$ states; - solving the problem directly as a mixed-integer linear program;
- using branch-and-bound or branch-and-cut;
- using approximation algorithms when an exact solution is unnecessary.
In a nondominated-state method, state
and
with at least one strict inequality. The dominated state
Such methods can handle non-integer weights, although the number of nondominated states may grow exponentially in the worst case [3].
One special situation is also worth noting. If all item weights are integers but the capacity is not, for example
then every feasible total weight is integer, so the constraint is equivalent to using
In summary:
integer / discretized weights and capacity
→ classical capacity-indexed DP
→ O(NV)
finite decimals or rational weights
→ scale to integers
→ exact DP, but the scaled capacity may become large
integer values but non-integer weights
→ value-indexed DP may be possible
general real-valued data
→ sparse-state DP, MILP, branch-and-bound, or approximation methods
There are
Each item can be used at most once.
The volume of item
We want to select a subset of items so that:
- the total volume does not exceed
$V$ ; - the total value is maximized.
Let
denote the maximum total value obtainable by choosing from the first
Then the state transition is
If
A useful way to understand the state
The set represented by
- items are chosen only from the first
$i$ items; - the total volume does not exceed
$j$ .
The property stored for this set is the maximum total value. In other dynamic-programming problems, the stored property could instead be a minimum value, a count, or another quantity.
To derive the state transition, partition the feasible selections into two disjoint cases according to whether item
If item
If item
Taking the better of these two cases gives
So every state is obtained by a simple set partition:
all feasible selections represented by f(i,j)
↓
exclude item i include item i
↓ ↓
f(i-1,j) f(i-1,j-v_i) + w_i
This “define the state set → identify the stored property → partition the set” viewpoint is a useful general method for constructing dynamic-programming recurrences.
The direct 2D dynamic program is:
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
v = [0] * (n + 1)
w = [0] * (n + 1)
for i in range(1, n + 1):
v[i] = next(it)
w[i] = next(it)
f = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(m + 1):
f[i][j] = f[i - 1][j]
if j >= v[i]:
f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i])
print(f[n][m])
if __name__ == "__main__":
solve()The time complexity is
and the space complexity is also
The 2D recurrence only uses the previous row, so we can reduce the state dimension from 2D to 1D.
Let
be the best value for capacity
Suppose the first
Therefore:
- the term
$f(i-1,j)$ is already stored in$f(j)$ , so copying it explicitly is unnecessary; - the transition involving item
$i$ only needs to be considered when$j\ge v_i$ , so the capacity loop can start from$v_i$ ; - the remaining candidate is obtained from
$f(j-v_i)+w_i$ .
This gives the compressed transition
However, after compression, the order of the capacity loop is crucial.
For 0-1 knapsack, we must traverse
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
v = [0] * (n + 1)
w = [0] * (n + 1)
for i in range(1, n + 1):
v[i] = next(it)
w[i] = next(it)
f = [0] * (m + 1)
for i in range(1, n + 1):
for j in range(m, v[i] - 1, -1):
f[j] = max(f[j], f[j - v[i]] + w[i])
print(f[m])
if __name__ == "__main__":
solve()Why must the loop go from large to small?
Because we need the transition to use the value from the previous layer:
not the already updated current-layer value.
If we loop
So for 0-1 knapsack:
Descending capacity order ensures that each item is used at most once.
There are
Each type of item can be used infinitely many times.
The volume of item type
We want to maximize the total value subject to the capacity constraint.
Let
denote the maximum value obtainable by using the first
Then the most direct recurrence is
This means that for item type
-
$0$ copies, -
$1$ copy, -
$2$ copies, - and so on,
as long as the total volume remains feasible.
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
v = [0] * (n + 1)
w = [0] * (n + 1)
for i in range(1, n + 1):
v[i] = next(it)
w[i] = next(it)
f = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(m + 1):
k = 0
while k * v[i] <= j:
f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i])
k += 1
print(f[n][m])
if __name__ == "__main__":
solve()The time complexity is
which is often written more simply as a three-loop dynamic program.
The naive recurrence can be rewritten more efficiently.
Expand the formula:
Now consider
Using the definition of
Therefore we obtain the important simplified recurrence:
This is the key difference from 0-1 knapsack.
Here the second term uses
not
This reflects the fact that item type
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
v = [0] * (n + 1)
w = [0] * (n + 1)
for i in range(1, n + 1):
v[i] = next(it)
w[i] = next(it)
f = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(m + 1):
f[i][j] = f[i - 1][j]
if j >= v[i]:
f[i][j] = max(f[i][j], f[i][j - v[i]] + w[i])
print(f[n][m])
if __name__ == "__main__":
solve()The same idea can be compressed into 1D.
Now the capacity loop must go from small to large:
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
v = [0] * (n + 1)
w = [0] * (n + 1)
for i in range(1, n + 1):
v[i] = next(it)
w[i] = next(it)
f = [0] * (m + 1)
for i in range(1, n + 1):
for j in range(v[i], m + 1):
f[j] = max(f[j], f[j - v[i]] + w[i])
print(f[m])
if __name__ == "__main__":
solve()Why ascending order this time?
Because we want the transition to use the current-layer value
which already accounts for the possibility of using item type
So for complete knapsack:
Ascending capacity order allows an item type to be reused.
There are
Item type
- volume
$v_i$ , - value
$w_i$ , - quantity limit
$s_i$ .
For the capacity-indexed DP used below, assume
We want to maximize total value subject to the capacity constraint.
Let
denote the maximum value obtainable by using the first
Then the direct recurrence is
This is almost the same as the complete knapsack recurrence, except that now the number of copies is limited by
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
v = [0] * (n + 1)
w = [0] * (n + 1)
s = [0] * (n + 1)
for i in range(1, n + 1):
v[i] = next(it)
w[i] = next(it)
s[i] = next(it)
f = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(m + 1):
k = 0
while k <= s[i] and k * v[i] <= j:
f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i])
k += 1
print(f[n][m])
if __name__ == "__main__":
solve()At first glance, the multiple knapsack problem looks very similar to the complete knapsack problem, so one may try to reuse the recurrence
But this is generally not valid.
The reason is that in the complete knapsack problem, item type
In the bounded knapsack problem, however, the number of copies of type
subject to the capacity limit.
If we try to use
which violates the quantity limit.
Therefore, repeated reuse of the current-layer state
So the complete-knapsack simplification does not preserve the quantity limit.
A standard optimization is to transform the bounded problem into a 0-1 knapsack problem by binary decomposition [2,3].
Suppose type
We split these copies into groups of sizes
until the remaining number is smaller than the next power of two.
For example, if
The important point is not that
With the bundle sizes
Each group becomes an artificial 0-1 item:
- group size
$k$ has volume$k v_i$ ; - group size
$k$ has value$k w_i$ .
Then choosing a subset of these artificial items is equivalent to choosing any number from
So the bounded knapsack problem becomes a 0-1 knapsack problem after decomposition.
If
After binary splitting, item type
time for the resulting 0-1 dynamic program.
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
items = []
for _ in range(n):
a = next(it) # volume
b = next(it) # value
s = next(it) # quantity
k = 1
while k <= s:
items.append((k * a, k * b))
s -= k
k <<= 1
if s > 0:
items.append((s * a, s * b))
f = [0] * (m + 1)
for vol, val in items:
for j in range(m, vol - 1, -1):
f[j] = max(f[j], f[j - vol] + val)
print(f[m])
if __name__ == "__main__":
solve()There are
Each group contains several candidate items, and at most one item may be selected from each group.
This is the grouped form used in this note and is closely related to the multiple-choice knapsack problem (MCKP) [3]. Some MCKP formulations require exactly one item from each group; the at-most-one version can be represented in that form by adding a zero-volume, zero-value dummy item to every group.
If item
For the capacity-indexed DP used below, assume the item volumes
We want to maximize total value subject to the capacity constraint.
Let
denote the maximum value obtainable from the first
Then the recurrence is
where
The first term corresponds to choosing nothing from group
The inner maximization corresponds to choosing one specific item from group
So for each group, we choose at most one item.
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
groups = [[] for _ in range(n + 1)]
for i in range(1, n + 1):
s = next(it)
for _ in range(s):
vol = next(it)
val = next(it)
groups[i].append((vol, val))
f = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(m + 1):
f[i][j] = f[i - 1][j]
for vol, val in groups[i]:
if j >= vol:
f[i][j] = max(f[i][j], f[i - 1][j - vol] + val)
print(f[n][m])
if __name__ == "__main__":
solve()The grouped knapsack problem can also be compressed to 1D.
The key point is the same as in 0-1 knapsack:
The capacity index must be scanned from large to small, so that the values used by the current group still come from the previous group.
Each group should be treated as one DP stage. If the capacity were scanned from small to large, a state already updated using one item from the current group could be reused when considering another item from that same group, which could incorrectly select more than one item from the group.
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
groups = []
for _ in range(n):
s = next(it)
group = []
for _ in range(s):
vol = next(it)
val = next(it)
group.append((vol, val))
groups.append(group)
f = [0] * (m + 1)
for group in groups:
for j in range(m, -1, -1):
for vol, val in group:
if j >= vol:
f[j] = max(f[j], f[j - vol] + val)
print(f[m])
if __name__ == "__main__":
solve()A useful summary is the following.
| Variant | Item availability | State transition idea | Capacity loop direction in 1D DP |
|---|---|---|---|
| 0-1 knapsack | each item at most once | take / do not take | descending |
| unbounded / complete knapsack | unlimited copies | reuse current item type | ascending |
| bounded knapsack | limited copies | enumerate copies or split into binary groups | descending after binary splitting |
| grouped / multiple-choice knapsack | at most one item per group | choose none or one from current group | descending |
This table captures the most important algorithmic difference among the standard knapsack variants.
For 0-1 and unbounded knapsack, the standard capacity-indexed dynamic programs run in
However, dependence on the numerical capacity
The reason is that the capacity
bits to encode it.
So an
This complexity also explains why the integer / discretized capacity assumption matters computationally. If decimal data are scaled by a factor
This is exactly why 0-1 knapsack can be NP-hard even though it admits a practical DP algorithm.
The ordinary 0-1 knapsack optimization problem is a classical example of a weakly NP-hard problem [3].
This means:
- it is NP-hard in general;
- but it admits a pseudo-polynomial dynamic program.
That is one of the main reasons the knapsack problem is used so often in algorithm courses and integer-programming courses.
- The knapsack problem is a classical resource-allocation problem under a capacity constraint.
- The decision version is NP-complete, while the optimization version is NP-hard.
- The classical
$O(NV)$ capacity-indexed DP assumes that weights and capacity are integer-valued or discretized to integers; the item values themselves do not need to be integers. - The central DP task is to define a good state and derive the correct recurrence.
- For 0-1 knapsack, the 1D capacity loop must go from large to small.
- For complete knapsack, the 1D capacity loop must go from small to large.
- Bounded knapsack can be efficiently reduced to a 0-1 knapsack problem by binary splitting, which replaces a copy-count decision by a logarithmic number of 0-1 bundle decisions.
- Grouped / multiple-choice knapsack treats each group as one stage; a descending capacity loop prevents selecting more than one item from the same group in the 1D implementation.
- The usual DP algorithms for knapsack are typically pseudo-polynomial, not polynomial in the encoded input length.
- Sun, Xiaoling, and Duan Li. Integer Programming. Beijing: Science Press, 2010. ISBN: 978-7-03-029380-0.(孙小玲、李端:《整数规划》,北京:科学出版社,2010年,ISBN:978-7-03-029380-0)
- Martello, Silvano, and Paolo Toth. Knapsack Problems: Algorithms and Computer Implementations. Chichester: John Wiley & Sons, 1990. ISBN: 978-0-471-92420-3.
- Kellerer, Hans, Ulrich Pferschy, and David Pisinger. Knapsack Problems. Berlin: Springer, 2004. DOI: 10.1007/978-3-540-24777-7.
- Merkle, Ralph C., and Martin E. Hellman. “Hiding Information and Signatures in Trapdoor Knapsacks.” IEEE Transactions on Information Theory 24(5), 1978, 525–530. DOI: 10.1109/TIT.1978.1055927.
- Bellman, R. Dynamic Programming. Princeton University Press, 1957. ISBN: 978-0-691-07951-6.
The most relevant next topics are:
-
Assignment Problem
A useful contrast to knapsack: it is also a structured combinatorial optimization problem, but unlike knapsack it admits polynomial-time algorithms. -
Approximation Algorithms
Especially relevant for NP-hard problems such as knapsack, where exact polynomial-time algorithms may not exist but high-quality solutions with provable guarantees can still be obtained. -
Branch and Bound / Branch and Cut
Useful for understanding how more general integer-programming methods solve knapsack-type models beyond pseudo-polynomial dynamic programming. -
Column Generation and Decomposition Methods
Helpful for seeing how very different large-scale optimization techniques compare with dynamic programming on special structures.