Intermediate Topic 26 of 51 Algorithms
Knapsack Problem
Choosing items under a capacity to maximize value.
How it works
In the 0/1 knapsack problem, each item has a weight and a value, and you choose a subset whose total weight fits the capacity W while maximizing total value. Dynamic programming fills a table dp[i][w] with the best value using the first i items and capacity w, running in O(nW) time, which is pseudo-polynomial because W is a number, not a length. The problem is NP-hard in general.
Where it is used
Budget allocation, cargo loading, selecting investments, cutting stock, resource scheduling and choosing features within effort limits use knapsack models. Variants include unbounded and fractional versions.
Common pitfall
Iterating capacity in the wrong direction in the one-dimensional table lets items be used more than once. Large capacities make the table huge. The fractional version is solved greedily by value-to-weight ratio, but the same greedy fails for the 0/1 version. Reconstructing the chosen items needs a back-pointer step.
Where it fits in the course
Knapsack Problem is topic 26 of 51 in Algorithms, rated Intermediate. It follows Dynamic Programming. The next topic is Longest Common Subsequence.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
- Explore the DP Table (LCS) visualizer: Watch the longest common subsequence table fill.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Knapsack Problem?
Where do people use Knapsack Problem?
What is the most common mistake with Knapsack Problem?
What should I learn before this topic?
How can I practice it?
Is Knapsack Problem hard to learn?
How long does it take to learn Knapsack Problem?
Which topics are related to Knapsack Problem?
What should I study after Knapsack Problem?
Related topics
- Dynamic Programming (Algorithms)
- Longest Common Subsequence (Algorithms)
- Greedy Algorithms (Algorithms)
- Edit Distance (Algorithms)
- Consensus Problem (Distributed Systems & Cloud)
- ABA Problem (Concurrency & Parallelism)
- Halting Problem (Theory & Discrete Math)