Dynamic Programming21 sections · 916 units
Open in Course

0/1 Knapsack - Implementation

The code

Here's the complete solution:

for i from 1 to n: for w from 0 to W: if w[i] <= w: dp[i][w] = max(dp[i-1][w], dp[i-1][w-w[i]] + v[i]) else: dp[i][w] = dp[i-1][w]
return dp[n][W]

Time: O(nW)O(n \cdot W). Space: O(nW)O(n \cdot W).

You can reduce space to O(W)O(W) by noticing each row only depends on the previous row. Process weights from WW down to 00 to avoid overwriting values you still need. The implementation follows directly from the transition formula. Each line of code corresponds to part of the mathematical formula.