Sub topic 1
What the Knapsack Problem Asks
The knapsack problem is a model for choosing under a budget. You have a set of items. Each item has a value and a weight. Your container has a fixed capacity. You want the selection with the highest total value whose total weight fits. The same structure shows up in many settings: choosing projects under a fixed budget, packing cargo, filling an ad slot, picking files for a backup disk, or allocating CPU time across jobs.
This chapter states the problem precisely and introduces the four variants used in the rest of the tutorial. It does not solve any of them. The goal here is a definition exact enough that you can tell whether a proposed answer is legal and what it is worth.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python: functions, loops, lists and tuples
- Recursion, which later chapters rely on
- Big-O notation for time and space
- Two-dimensional arrays or nested lists, which come up once the DP table appears
You do not need any prior knowledge of dynamic programming or optimization.
The ingredients of an instance
An instance of the knapsack problem has these parts:
- n items, numbered 0 to n − 1.
- A value vᵢ ≥ 0 for each item i: what you gain by packing it.
- A weight wᵢ > 0 for each item i: how much capacity it uses.
- A capacity W ≥ 0: the most total weight the knapsack can hold.
A solution assigns an amount xᵢ to each item, meaning how much of item i you pack. The objective is to maximize the total value Σ vᵢ·xᵢ. The single constraint is Σ wᵢ·xᵢ ≤ W. A solution that meets the constraint is feasible. A feasible solution with the largest possible objective is optimal.
The variants differ only in which values xᵢ is allowed to take. That one detail decides whether a simple greedy rule works, which DP loop you write, and how hard the problem is in theory.
The four variants
0/1 knapsack
Each item is either taken whole or left behind: xᵢ ∈ {0, 1}. This is the classic version, and "the knapsack problem" with no qualifier usually means this one. Most of the tutorial focuses on it.
Fractional knapsack
You may take any fraction of an item: 0 ≤ xᵢ ≤ 1. Think of gold dust or bulk grain instead of gold bars. Taking half an item gives half its value and uses half its weight.
Unbounded knapsack
Each item is a type with unlimited supply: xᵢ ∈ {0, 1, 2, …}. You may pack the same item as many times as the capacity allows. Coin-change and rod-cutting problems have this shape.
Bounded knapsack
Item i has a limited stock of kᵢ copies: xᵢ ∈ {0, 1, …, kᵢ}. This sits between 0/1 (every kᵢ = 1) and unbounded (every kᵢ effectively infinite).
| Variant | Allowed amounts xᵢ | Typical example | Solved in this tutorial by |
|---|---|---|---|
| 0/1 | 0 or 1 | Choosing projects, packing distinct objects | Dynamic programming |
| Fractional | Any real in [0, 1] | Divisible goods such as liquids and powders | Greedy by value per weight |
| Unbounded | Any integer ≥ 0 | Coin change, cutting stock | DP with forward iteration |
| Bounded | Integer from 0 to kᵢ | Warehouse stock with limited copies | Binary splitting into 0/1 items |
A running example
The rest of the tutorial uses one small instance:
| Item | Value | Weight | Value per weight |
|---|---|---|---|
| 0 | 60 | 10 | 6.0 |
| 1 | 100 | 20 | 5.0 |
| 2 | 120 | 30 | 4.0 |
The capacity is W = 50. The best answer differs for each variant:
- 0/1: take items 1 and 2, with weight 50 and value 220.
- Fractional: take items 0 and 1 whole and two-thirds of item 2, with weight 50 and value 240.
- Unbounded: take five copies of item 0, with weight 50 and value 300.
- Bounded with stock (2, 1, 1): take two copies of item 0 and one of item 2, with weight 50 and value 240.
The ordering 0/1 ≤ bounded ≤ unbounded holds in general, because each variant allows every solution of the one before it. The fractional optimum is also always at least the 0/1 optimum. That fact is the basis for the upper bound used in branch and bound later on.
Checking a proposed solution
Before solving anything, it helps to have code that checks whether an answer is legal and computes its value. The function below does this for all four variants. It uses Fraction so the fractional case gives exact results with no floating-point rounding.
from fractions import Fraction
def evaluate(values, weights, capacity, x, variant="0/1", counts=None):
"""Return the total value of amounts x, or raise ValueError if illegal."""
if len(x) != len(values):
raise ValueError("one amount per item is required")
for i, amount in enumerate(x):
if variant == "0/1":
ok = amount in (0, 1)
elif variant == "fractional":
ok = 0 <= amount <= 1
elif variant == "unbounded":
ok = isinstance(amount, int) and amount >= 0
elif variant == "bounded":
ok = isinstance(amount, int) and 0 <= amount <= counts[i]
else:
raise ValueError(f"unknown variant {variant!r}")
if not ok:
raise ValueError(f"amount {amount} not allowed for item {i} in {variant} knapsack")
used = sum(w * a for w, a in zip(weights, x))
if used > capacity:
raise ValueError(f"weight {used} exceeds capacity {capacity}")
return sum(v * a for v, a in zip(values, x))
V, W = [60, 100, 120], [10, 20, 30]
print(evaluate(V, W, 50, [0, 1, 1])) # 220
print(evaluate(V, W, 50, [1, 1, Fraction(2, 3)], "fractional")) # 240
print(evaluate(V, W, 50, [5, 0, 0], "unbounded")) # 300
print(evaluate(V, W, 50, [2, 0, 1], "bounded", counts=[2, 1, 1])) # 240
try:
evaluate(V, W, 50, [1, 1, 1])
except ValueError as e:
print(e) # weight 60 exceeds capacity 50Checking a solution is fast: O(n) time. Finding the best one is the hard part. That gap between checking and finding is what makes the 0/1 problem NP-hard, which a later chapter covers.
Conventions and edge cases
Small differences in how the problem is stated change the algorithms. These are the conventions this tutorial uses, and the cases that break code when they are ignored.
Integer weights and capacity
The DP chapters index arrays by capacity, so weights and W must be non-negative integers. If your weights are prices like 19.99, scale them to integers (cents) first. Real-valued weights call for value-indexed DP or branch and bound instead.
"At most" versus "exactly"
The constraint here is Σ wᵢxᵢ ≤ W. Some problems require the weight to equal W exactly, for example "can these coins make exactly 37?" With the exact version, some capacities cannot be reached at all. The DP must then start unreachable states at −∞ instead of 0. Mixing the two conventions up is a common bug.
Degenerate inputs
- Empty item list or W = 0: the only feasible choice is taking nothing, so the optimum is 0.
- An item heavier than W: it can never be taken. It is harmless, but your code must not index a negative capacity.
- Zero-weight items: in the 0/1 case, take every one that has positive value. In the unbounded case, a zero-weight item with positive value makes the optimum infinite, so the problem is ill-posed. This is why the definition requires wᵢ > 0.
- Ties: several different selections can share the optimal value. Algorithms return one of them, and which one depends on loop order.
Optimization versus decision
The optimization version asks for the largest value. The decision version asks whether some feasible selection reaches at least a target value T. The two are equally hard up to a binary search over T. Complexity theory usually talks about the decision version. When every value equals its weight, the decision version becomes subset sum: is there a subset whose weights add up to exactly a target?
Exercises
Exercise
A student can study for 6 hours. Topic A takes 2 hours and is worth 5 marks, topic B takes 3 hours for 7 marks, and topic C takes 4 hours for 9 marks. Each topic is studied fully or not at all. Name the variant, write the instance as values, weights and capacity, and find the optimum by hand.
Show answer
This is 0/1 knapsack with values [5, 7, 9], weights [2, 3, 4] and W = 6. The feasible pairs are A+B (5 hours, 12 marks) and A+C (6 hours, 14 marks). B+C needs 7 hours, which is too many. The optimum is A+C with 14 marks.
Exercise
Using the running example (values [60, 100, 120], weights [10, 20, 30], W = 50), explain why the unbounded optimum of 300 can never be beaten by the 0/1 optimum on any instance, and give a selection that is feasible for bounded knapsack with stock (2, 1, 1) but not for 0/1.
Show answer
Every 0/1 solution is also an unbounded solution, because amounts of 0 or 1 are non-negative integers. So the unbounded maximum is taken over a larger set and cannot be smaller. The selection x = (2, 0, 1) uses two copies of item 0. It is legal under stock (2, 1, 1), with weight 50 and value 240, but illegal in 0/1, where xᵢ must be 0 or 1.
Exercise
Suppose an unbounded knapsack instance contains an item with weight 0 and value 5. What is the optimal value, and what does this tell you about the definition?
Show answer
You can pack unlimited copies at no cost in capacity, so the value grows without bound and there is no optimum. That is why the definition requires every weight to be strictly positive. In 0/1 knapsack the same item is harmless: you take it once and gain 5.