A budget for the best combination.
Choose items once each and update capacity states in the correct direction.
01 Model the idea
In 0/1 knapsack, each item can be selected at most once. The objective is maximum total value without exceeding capacity. A DP state records the best value available for a capacity after considering a prefix of items. With a one-dimensional table, iterate capacities downward so the current item cannot feed another state that uses it again.
After an item pass, each state is optimal using only items considered so far.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FOR each item
VISIT capacities from high to low
choose between skipping and taking the item once| Items considered | Capacity 5 best value |
|---|---|
| None | 0 |
| (2,4) | 4 |
| (2,4), (3,5) | 9 |
| All three items | 9 |
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def knapsack(items, capacity):
best = [0] * (capacity + 1)
for weight, value in items:
if weight <= 0: raise ValueError("Positive item weights required")
for available in range(capacity, weight - 1, -1):
best[available] = max(best[available], best[available - weight] + value)
return best[capacity]
print(knapsack([(2, 4), (3, 5), (4, 7)], 5))9
- 1
The item pair is weight then value. Selecting the first two items uses capacity five and produces value nine.
- 2
Descending capacity order keeps best[available-weight] from already containing the same current item. Ascending order would implement a different, unbounded reuse pattern.
- 3
The O(nW) bound depends on numeric capacity W, which can be exponentially large relative to its bit representation. This is called pseudo-polynomial time, not a general polynomial solution to the decision problem.
04 Count the cost
O(nW) for n items and capacity W; pseudo-polynomial
O(W)
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Check that an item too heavy to fit contributes nothing and that capacity zero returns zero.
Reveal one possible solution +
def knapsack(items, capacity):
best = [0] * (capacity + 1)
for weight, value in items:
for available in range(capacity, weight - 1, -1):
best[available] = max(best[available], best[available - weight] + value)
return best[capacity]
assert knapsack([(2, 4)], 1) == 0
assert knapsack([(2, 4)], 0) == 0
print("Capacity boundaries passed")06 Check your reasoning
Why update capacity downward for 0/1 knapsack?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.