0-1 knapsack

Take it or leave it Β· Part of Strategies

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Knapsack problem

There are n items, each with a weight and a value, and a knapsack with capacity cap. You want the highest total value without going over the capacity, and each item can be taken at most once: that is why it is called 0-1. It is a sequence of n decisions, skip or take, so it fits a decision tree. With capacity 4 and items of weight 1, 2 and 3 worth 5, 11 and 15, the best is to take the weight-1 and weight-3 items: value 20.

Skipping an item does not change the free capacity; taking it shrinks it. That is why the state has 2 variables: the item number i and the free capacity c, [i, c]. dp[i, c] is the highest value with the first i items and a knapsack of capacity c. The answer is dp[n, cap], and the table has (n + 1) Γ— (cap + 1) cells: with 3 items and capacity 4, 4 Γ— 5 = 20.

Since each row only uses the previous one, 2 lists are enough, and memory goes from O(n Γ— cap) to O(cap). You can even use a single list, but walking the capacities from largest to smallest. If you walk from smallest to largest, the value above and to the left has already been overwritten with the new row's, and an item gets counted twice. Example: an item of weight 1 and value 5, capacity 2. Going forward, dp[2] = dp[1] + 5 = 10; going backward, it gives 5, which is correct.

State transition equation

When deciding on item i there are 2 cases. Skip it: the capacity stays the same and you move to [i βˆ’ 1, c]. Take it: the capacity drops by wgt[i βˆ’ 1], the value rises by val[i βˆ’ 1], and you move to [i βˆ’ 1, c βˆ’ wgt[i βˆ’ 1]]. The best value is the larger of the 2: dp[i, c] = max(dp[i βˆ’ 1, c], dp[i βˆ’ 1, c βˆ’ wgt[i βˆ’ 1]] + val[i βˆ’ 1]). If the item weighs more than c, it can only be skipped.

Dynamic programming

With no items or capacity 0, the best value is 0: row dp[0, c] and column dp[i, 0] are 0. State [i, c] depends on [i βˆ’ 1, c], right above, and on [i βˆ’ 1, c βˆ’ wgt[i βˆ’ 1]], above and to the left. That is why the table is walked with 2 for loops in increasing order. With weights [1, 2, 3] and values [5, 11, 15], row 1 becomes 0, 5, 5, 5, 5 and row 2 becomes 0, 5, 11, 16, 16.

Time complexity

With brute force, each item opens 2 branches, skip and take: O(2ⁿ). The tree repeats subproblems, like dp[1, 10], especially when several items weigh the same. With memoization, each state is solved once, and the time depends on the number of states: O(n Γ— cap). Dynamic programming is also O(n Γ— cap) in time and memory. With 100 items and capacity 1,000: about 100,000 steps instead of 2¹⁰⁰.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Take it or leave it