Knapsack problem
- Algorithms course
- Advanced
- Lesson 13/56
- 4 min
Fill a capacity with weighted, valuable items.
Knapsack problem
Knapsack: given items with weight and value, fill the capacity without exceeding it to maximize value.
0/1 knapsack: each item is either taken or not; no splitting.
Knapsack is used in resource allocation and investment decisions; a classic DP problem.
0/1 vs fractional
In 0/1 knapsack an item is either taken or not. In fractional knapsack items can be split; greedy is optimal.
0/1 knapsack requires dynamic programming; greedy is not always optimal.
This distinction determines which method to apply; an important choice.
Practice Knapsack brute
Write knap_brute(W, weights, values, n). Recursive brute-force 0/1 knapsack. Print 220 with print(knap_brute(50, [10, 20, 30], [60, 100, 120], 3)).
Starter code
def knap_brute(W, weights, values, n):
# Knapsack bruteSample solution
def knap_brute(W, weights, values, n):
# Knapsack brute
if n == 0 or W == 0:
return 0
if weights[n - 1] > W:
return knap_brute(W, weights, values, n - 1)
take = values[n - 1] + knap_brute(W - weights[n - 1], weights, values, n - 1)
skip = knap_brute(W, weights, values, n - 1)
return max(take, skip)
print(knap_brute(50, [10, 20, 30], [60, 100, 120], 3))Expected output
220
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is each item handled in 0/1 knapsack?
- Half taken
- Split
- Divided
- Either taken or not Correct answer
Explanation: Either taken or not.
2 Capacity exceed
if w > ____:
if w > capacity:
Explanation: capacity is right.
3 Knapsack problem: match the terms
| Term | Meaning |
|---|---|
knapsack |
Knapsack |
weight |
Weight |
value |
Value |
capacity |
Capacity |