Knapsack & Subset Thinking
What is this?
Knapsack-style DP is about choosing a subset of items to get the best value while staying under some limit — for each item you decide "take it or leave it," and you reuse the best answers for smaller limits instead of re-trying every combination. Imagine packing a bag with a weight cap and wanting the most value inside. The second, sharper lesson here is that some problems only look like knapsack and actually fold down to a one-line counting observation, so it pays to look before you build a whole table.
💡 Fun fact: The 0/1 knapsack problem is NP-hard in general, yet the table-filling DP solves it quickly when the capacity is a modest whole number — a famous case where a problem is "hard" in theory but tame for the sizes interviewers actually ask about.
🔓 The 1 problem in this chapter is free. Sign in with Google or Microsoft to start solving.
Core idea: Knapsack-style problems ask you to choose a subset of items to optimize a value under a capacity/constraint — the home of the classic "take it or leave it" DP. But this bucket carries a second, sharper lesson: some problems look like knapsack/DP and actually collapse to a one-line counting insight. Always check for the shortcut before building a table.
Take-it-or-leave-it, and the shortcut
Recognizing structure (equal values move in lockstep, a quantity is just a count of distinct levels) can replace an O(n·W) table with an O(n) observation. The skill is knowing which situation you're in.
The problem
- Make Array Zero by Subtracting Equal Amounts — filed under knapsack/DP, but the answer is simply the number of distinct nonzero values (each operation peels one level). A clean example of beating a heavy DP framing with a counting insight.
The full 0/1 and unbounded knapsack DPs (subset-sum, partition, bounded coin variants) build directly on the take-it-or-leave-it recurrence and the unbounded version you met in Coin Change.
Key takeaways
- Knapsack = choose a subset under a constraint, via a take-it-or-leave-it recurrence.
- Check for a counting/greedy shortcut first — not everything filed as DP needs a table.
- Structure beats brute — equal/lockstep values and "distinct levels" often collapse the problem.
- Why interviewers love it: they want to see whether you reach for the right tool, not the heaviest one.
Problem: Make Array Zero by Subtracting Equal Amounts.