Lesson 1 · Unit 04
0/1 knapsack
Take or skip each item under a weight limit
What you practise
- Take or skip under a capacity
- Why the 1D version loops capacity downward
Try a question from this lesson
Pick one
A bag holds 5 kg. Items (weight, value): (1 kg, 15), (3 kg, 20), (4 kg, 30). Each item is taken whole or left behind. What is the best total value?
Correct answer
45
Why
The 1 kg and 4 kg items fill the bag exactly for 15 + 30 = 45. The 3 kg and 4 kg items would give 50 but weigh 7 kg. Taking the first two gives only 35, with a kilo of room wasted.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Take it or skip it, with a limit
The state needs two numbers: which item you are deciding on, and how much capacity is left.
Skip item i and the capacity is unchanged. Take it, if it fits, and you gain its value but have less room for the rest. The answer is the better of the two. A memo keyed on both numbers stops repeated states.
items = [(1, 15), (3, 20), (4, 30)]
def best(i, cap):
if i == len(items):
return 0
w, v = items[i]
skip = best(i + 1, cap)
if w > cap:
return skip
take = v + best(i + 1, cap - w)
return max(skip, take)
print(best(0, 5))const items = [[1, 15], [3, 20], [4, 30]];
function best(i, cap) {
if (i === items.length) return 0;
const [w, v] = items[i];
const skip = best(i + 1, cap);
if (w > cap) return skip;
const take = v + best(i + 1, cap - w);
return Math.max(skip, take);
}
console.log(best(0, 5));const items = [[1, 15], [3, 20], [4, 30]];
function best(
i: number,
cap: number,
): number {
if (i === items.length) return 0;
const [w, v] = items[i];
const skip = best(i + 1, cap);
if (w > cap) return skip;
const take = v + best(i + 1, cap - w);
return Math.max(skip, take);
}
console.log(best(0, 5));Python notew, v = items[i] unpacks the (weight, value) tuple into two names.
JavaScript noteconst [w, v] = items[i] is array destructuring: the first entry goes to w, the second to v.
TypeScript noteA recursive function needs its return type written out (): number): TypeScript cannot infer it from a body that calls itself.
Concept
One row, filled backwards
Bottom-up, dp[c] is the best value for capacity c using the items handled so far. Each item updates the row in place.
The capacity loop runs downward on purpose. dp[c - w] is then still the value from before this item, so the item cannot be added on top of itself.
def knapsack(items, cap):
dp = [0] * (cap + 1)
for w, v in items:
for c in range(cap, w - 1, -1):
take = dp[c - w] + v
dp[c] = max(dp[c], take)
return dp[cap]function knapsack(items, cap) {
const dp = Array(cap + 1).fill(0);
for (const [w, v] of items) {
for (let c = cap; c >= w; c--) {
const take = dp[c - w] + v;
dp[c] = Math.max(dp[c], take);
}
}
return dp[cap];
}function knapsack(
items: number[][],
cap: number,
): number {
const dp = Array<number>(cap + 1)
.fill(0);
for (const [w, v] of items) {
for (let c = cap; c >= w; c--) {
const take = dp[c - w] + v;
dp[c] = Math.max(dp[c], take);
}
}
return dp[cap];
}Python noterange(cap, w - 1, -1) counts down from cap and stops at w, the smallest capacity this item fits in.
TypeScript noteitems: number[][] is a list of [weight, value] pairs. Destructuring in the for...of gives w and v the type number.
9 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
- 2× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.