0/1 Knapsack
Intermediate · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The 0/1 knapsack picks items, each used at most once, to get the greatest total value without exceeding a weight or budget limit. For each item and each capacity you decide whether to leave it or take it. It is the model for every "best use of a limited budget" decision.
Practical use cases
- Web app: Choosing features for a sprint. A project tool lets a team pick tasks for a two-week sprint with 40 hours available, where each task has a time estimate and a business value. The code finds the combination of tasks with the most value that fits in 40 hours. Product managers see a suggested plan instead of arguing over a spreadsheet.
- Web app: Video playlist or course fit. A learning portal lets a student say "I have 3 hours tonight" and suggests lessons with the most learning points that fit in that time, using each lesson once. The page responds instantly because a table already holds the best answer for every smaller time limit, so changing it to 90 minutes needs no new calculation.
- System: Cargo loading and budget planning. Logistics software chooses which parcels to load in a truck with a weight limit to maximise revenue. Finance tools choose projects within a budget. In each of these, the real task is choosing from a menu of options under a hard limit, and the take-or-leave table beats grabbing the best-looking items first.
The story: Mira Packs for the Trek
Mira's class was going on a hill trek, and her bag could carry only 7 kilos. On her bed lay four things: a laddoo box (1 kg, a little useful), a water can (3 kg, quite useful), a blanket (4 kg, useful), and a camera (5 kg, very useful). Each existed only once. Take it or leave it, no cutting the blanket in half.
Kabir said, "Take the most useful first: the camera. Then the blanket? No, that's over 7. The water can? Over. Just the laddoo box..." His score was 8. Mira did not trust a rule like that. "Let's try something more careful. Imagine a row of bags with sizes 0 to 7 kg. We add the items one at a time. After each new item, we write down, for every bag size, the best value we can get."
For a new item, each bag size has just two choices: leave the item (the answer is the same as before the item came), or take it (its value, plus the best we could do with the lighter bag that remains after making room for it). Mira picked the larger every time. After four rows, the bottom-right box said 9: the water can plus the blanket. Better than Kabir's 8.
This is the 0/1 knapsack: "0 or 1" because each item is taken 0 times or 1 time. It is the most famous DP problem, and its pattern (state = items considered so far and room left, choice = take or leave) appears everywhere.
How to spot this problem, and where you need it
You have a set of things, each with a cost and a benefit, a limited budget, and you must choose which ones to take for the most benefit, taking each at most once.
Signs you need it
- The problem has weights or costs, values, and a capacity or budget, with each item used once or not at all.
- Picking the best value-per-cost items first does not always give the best total.
- Trying all subsets works for 15 items but not for 50.
Where to use it in a project
- Sprint, budget or resource planning tools that choose the best set of tasks or projects.
- Recommendation features that fit the most valuable content into a time or size limit.
The solution
Make a table with one row per item and one column per capacity from 0 up to the limit. Each cell is the best value using the first i items within that capacity. For each cell, take the larger of two choices: leave the item (copy the value from the row above) or take it (its value plus the best value above at the capacity minus its weight). The bottom-right cell holds the best total.
Payoff: Before: checking about a billion subsets for 30 tasks. After: a table of 30 rows by 40 hours, about 1,200 cells.
Explain it like I am 8
You have a lunchbox with limited space and many snacks on the table. Go through the snacks one by one. For each snack and each possible lunchbox size, ask: "Do I leave it, or do I take it and squeeze it in?" You write the better answer on a grid, and the last square shows the best lunch.
How it works, step by step
- State:
dp[i][c]= the best total value using only the firstiitems with a bag that holdsckilos. - Base case:
dp[0][c] = 0(no items, no value) anddp[i][0] = 0(no room, nothing fits). - Transition: leave it
dp[i-1][c], or take itdp[i-1][c - w] + vif the item fits (w <= c). Keep the larger. - Fill row by row (item by item). The answer is
dp[n][W], the bottom-right box. - Space trick: each row only reads the previous row, so one row is enough if you fill bag sizes from big to small, so a box never uses an item it already took.
The code in four languages
PHP
<?php
// 0/1 knapsack: each item is taken once or not at all.
// dp[i][c] = best value using the first i items with room c.
function knapsack(array $weights, array $values, int $cap): int {
$n = count($weights);
$dp = array_fill(0, $n + 1, array_fill(0, $cap + 1, 0)); // row 0 and column 0 stay 0
for ($i = 1; $i <= $n; $i++) {
$w = $weights[$i - 1];
$v = $values[$i - 1];
for ($c = 0; $c <= $cap; $c++) {
$dp[$i][$c] = $dp[$i - 1][$c]; // leave the item
if ($w <= $c) { // take the item, if it fits
$dp[$i][$c] = max($dp[$i][$c], $dp[$i - 1][$c - $w] + $v);
}
}
}
return $dp[$n][$cap];
}
echo knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7), "\n"; // 9 (water can + blanket)JavaScript
// 0/1 knapsack: each item is taken once or not at all.
// dp[i][c] = best value using the first i items with room c.
function knapsack(weights, values, cap) {
const n = weights.length;
const dp = Array.from({ length: n + 1 }, () => new Array(cap + 1).fill(0)); // row 0 and column 0 stay 0
for (let i = 1; i <= n; i++) {
const w = weights[i - 1], v = values[i - 1];
for (let c = 0; c <= cap; c++) {
dp[i][c] = dp[i - 1][c]; // leave the item
if (w <= c) { // take the item, if it fits
dp[i][c] = Math.max(dp[i][c], dp[i - 1][c - w] + v);
}
}
}
return dp[n][cap];
}
console.log(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)); // 9 (water can + blanket)Java
public class Main {
// 0/1 knapsack: each item is taken once or not at all.
// dp[i][c] = best value using the first i items with room c.
static int knapsack(int[] weights, int[] values, int cap) {
int n = weights.length;
int[][] dp = new int[n + 1][cap + 1]; // row 0 and column 0 stay 0
for (int i = 1; i <= n; i++) {
int w = weights[i - 1];
int v = values[i - 1];
for (int c = 0; c <= cap; c++) {
dp[i][c] = dp[i - 1][c]; // leave the item
if (w <= c) { // take the item, if it fits
dp[i][c] = Math.max(dp[i][c], dp[i - 1][c - w] + v);
}
}
}
return dp[n][cap];
}
public static void main(String[] args) {
System.out.println(knapsack(new int[]{1, 3, 4, 5}, new int[]{1, 4, 5, 7}, 7)); // 9 (water can + blanket)
}
}Go
package main
import "fmt"
// 0/1 knapsack: each item is taken once or not at all.
// dp[i][c] = best value using the first i items with room c.
func knapsack(weights, values []int, cap int) int {
n := len(weights)
dp := make([][]int, n+1) // row 0 and column 0 stay 0
for i := range dp {
dp[i] = make([]int, cap+1)
}
for i := 1; i <= n; i++ {
w, v := weights[i-1], values[i-1]
for c := 0; c <= cap; c++ {
dp[i][c] = dp[i-1][c] // leave the item
if w <= c { // take the item, if it fits
dp[i][c] = max(dp[i][c], dp[i-1][c-w]+v)
}
}
}
return dp[n][cap]
}
func main() {
fmt.Println(knapsack([]int{1, 3, 4, 5}, []int{1, 4, 5, 7}, 7)) // 9 (water can + blanket)
}Time: O(n × W) · Extra space: O(n × W). One box per (item, bag size) pair. A single row (filled from big to small) cuts space to O(W).
Watch out for
- Trying "take the highest value first" (greedy). It misses better combinations, as in the story.
- Reading
dp[i-1][c - w]without checkingw <= c, which goes below column 0. - In the one-row version, looping bag sizes from small to big. That lets one item be used many times (that is the unbounded version).
Quick check
- What does "0/1" in 0/1 knapsack mean?
- Each item can be taken at most once
- Values are only 0 or 1
- The bag has two sizes
- For a given item and bag size, what are the two choices?
- Sort it or shuffle it
- Leave it, or take it and add its value to the best of the smaller bag
- Take it twice or three times
- Where is the final answer?
- Top-left box
- Bottom-right box (all items, full bag)
- The biggest weight