What is the 0/1 Knapsack Problem?
The 0/1 Knapsack Problem asks: given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity, which items should be chosen to maximize the total value without exceeding the capacity? Each item can either be taken whole or left behind entirely - it cannot be split, hence "0/1".
A brute-force solution would try every possible subset of items, giving O(2^n) time complexity. Dynamic Programming avoids this by building a table where dp[i][w] represents the best value achievable using the first i items with capacity w, reusing previously solved subproblems just like in the Fibonacci Sequence visualizer.
Time & Space Complexity
- Brute ForceO(2^n)
- DP TimeO(n · W)
- DP SpaceO(n · W)
- Optimized SpaceO(W)
* n = number of items, W = knapsack capacity. This is "pseudo-polynomial" because it depends on the magnitude of W, not just the input size.
Real-World Use Cases
- ✓Resource AllocationChoosing projects or investments under a fixed budget to maximize return.
- ✓Cargo & LogisticsLoading shipments to maximize value while respecting weight limits.
- ✓Memory-Constrained SystemsSelecting which assets or features to load within a fixed memory budget.