Lessons 6–10 · About 60 min per lesson
Knapsack and 2D dynamic programming
Design two-dimensional states for capacity or grid positions, then decide when compression is valid.
Lesson breakdown
- Lesson 6
Define 0/1 knapsack states by item index and capacity.
- Lesson 7
Derive the take and skip transitions.
- Lesson 8
Use descending capacity in a one-dimensional table to prevent reusing an item.
- Lesson 9
Count grid paths with obstacles using the state above and to the left.
- Lesson 10
Test one item, zero capacity and unreachable cells.
Worked example
A 0/1 knapsack holds 4. There is one item of weight/value (2,3) and one of (3,4). Find the best value.
How to solve it
Both weigh 5 together, so take only the second for value 4. An incorrect update might reuse the first item and report an invalid 6.
Assignment
Implement compressed 0/1 knapsack and compare against subset enumeration on small inputs. Weights are positive.
Check your result
Capacity 4 with only (2,3) → 3; capacity 5 with both example items → 7; capacity 0 → 0.