0/1 Knapsack
Given item weights and values and a knapsack capacity, maximise the total value carried. Each item may be taken at most once.
Open on GeeksforGeeks ↗Intuition
Greedy by value-to-weight ratio is the natural first instinct and it is wrong here, because capacity must be packed as a whole rather than filled proportionally — a slightly worse ratio can fit the remaining space exactly. Instead ask one binary question per item: take it or skip it. Skipping leaves the same capacity with fewer items; taking spends its weight and leaves a strictly smaller capacity. Both branches are smaller subproblems, so a table over (items considered, capacity) solves each exactly once.
Approach
Two-dimensional state
dp[i][c] = best value using only the first i items within capacity c. Row 0 is all zeros — no items, no value.
Take or skip
If the item fits, dp[i][c] = max(skip, take) where skip = dp[i-1][c] and take = value[i] + dp[i-1][c - weight[i]]. If it does not fit, only skip is available.
Why the previous row
Both branches read row i-1, never row i. That is exactly what enforces 'at most once' — an item can never be consulted after it has been taken.
Solution & live demo
Edge cases
Column 0 stays 0 — nothing fits, so no value is achievable.
weight > c in every column, so the value is inherited unchanged from the row above.
Every take branch wins and the answer is the sum of all values.