Dynamic Programming

Problem shape

Intermediate
4
8
15
16
23
42
Core idea

For each item and capacity, choose between skipping or taking the item.

Step 1 / 5
Problem shape
Current lesson

0/1 Knapsack Lab

Dynamic Programming Intermediate

0/1 Knapsack

Welcome to the 0/1 Knapsack algorithm lab. For each item and capacity, choose between skipping or taking the item. Use it when: Use when items are indivisible and capacity is limited. The time complexity is O(nW), and the space complexity is O(nW) or O(W). The pseudocode is: for item in items for cap from W down to item.weight dp[cap] = max(dp[cap], dp[cap - weight] + value) As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(nW)

Space

O(nW) or O(W)

Pseudocode

for item in items
  for cap from W down to item.weight
    dp[cap] = max(dp[cap], dp[cap - weight] + value)
Open deeper structure lesson
1.0x