intermediate9 min read·Updated October 4, 2026

0/1 Knapsack Explained: Packing Weights [1,2,3] up to Capacity 5

Master the 0/1 knapsack problem with a step-by-step DP table walkthrough using items [1,2,3], values [6,10,12], and W=5. Build robust mental models.

By Learnisim AI·Published October 4, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
  • Basic 2D array indexing
  • Familiarity with recurrence relations
  • Understanding of memoization vs tabulation
0/1 Knapsack Optimization: Weights [1,2,3], Values [6,10,12], W = 5 Available Items Item 1: wt=1, val=6 r=6.0 Item 2: wt=2, val=10 r=5.0 Item 3: wt=3, val=12 r=4.0 Why Greedy Fails Ratio Sort (Item 1 + Item 2) Wt: 3, Val: 16 (Spare Wt: 2) Optimal Combo (Item 2 + Item 3) Wt: 5, Val: 22 (Max Value!) DP Transition Formula DP[c] = max(DP[c], DP[c - w_i] + v_i) Backwards iteration prevents item reuse Explores exact capacity limits 0 to 5 Tracing the DP Table: Step-by-Step Backwards Execution (W = 5) Capacity c: c = 0 c = 1 c = 2 c = 3 c = 4 c = 5 Init (All 0): 0 0 0 0 0 0 After Item 1: 0 6 6 6 6 6 After Item 2: 0 6 10 16 16 16 After Item 3: 0 6 10 12 18 22
Weights [1,2,3], values [6,10,12], W = 5 overview diagram
Why

Why Greedy Fails: The Puzzle of Packing Finite Weight

Phase 1: The Packing Dilemma

Imagine you are packing a cargo pod with a strict weight limit of kilograms. You have three discrete items to choose from. Item 1 weighs and is worth 6. Item 2 weighs and is worth 10. Item 3 weighs and is worth 12. You cannot split items into fractions, and you cannot take duplicates of the same item. Your goal is to maximize the total value without exceeding your weight limit of .
If you rely on a naive greedy approach—such as picking the item with the highest value-to-weight ratio first—you might immediately grab Item 1 (), then Item 2 (), leaving you with a total weight of and a value of 16. You have of spare capacity, but Item 3 weighs , so it won't fit. Alternatively, if you pick the single most valuable item first, you might grab Item 3 (12), leaving capacity, which lets you take Item 1 (6) for a total value of 18.
Yet, the optimal combination for this setup yields a total value of 22 by packing Item 2 and Item 3 together. This combinatorial explosion of choices explains why simple sorting fails us and why we need a systematic way to explore weight constraints without testing every single permutation by hand.
Why Greedy Fails: The Puzzle of Packing Finite Weight (W = 5) Comparing ratio-greedy vs. optimal dynamic programming choice Available Items (No splits) Item 1 1kg | Val 6 Ratio: 6.0 Item 2 2kg | Val 10 Ratio: 5.0 Item 3 3kg | Val 12 Ratio: 4.0 Naive Greedy Approach (Sort by Ratio) Pick Item 1 Wt: 1, Val: 6 Pick Item 2 Wt: 2, Val: 10 Result: Suboptimal Trap! • Total Weight Used: 3 kg (out of 5 kg) • Total Value Achieved: 16 Capacity left (2kg), but Item 3 (3kg) doesn't fit! Optimal Solution (Items 2 + 3) Pack Item 2 Wt: 2 kg, Val: 10 Pack Item 3 Wt: 3 kg, Val: 12 Result: Maximum Value! • Total Weight Used: 5 kg (Exact capacity!) • Total Value Achieved: 22 (10 + 12) Beats greedy result (16) by bypassing ratio trap. Strict Constraint Pod Limit: W = 5 kg Why can't we just pick the best ratio? Because discrete items cannot be split. Combinatorial search or DP explores all subsets to find exact maxima. Optimal Capacity Used: 5 / 5 kg
Why Greedy Fails: The Puzzle of Packing Finite Weight diagram
Model

Building the Core Mental Model for Resource Allocation

Phase 2: The Decision Grid and State Space

When we look at our locked working example with items , , and under a capacity , every single item presents a fundamental binary question: do we include it or exclude it? Unlike continuous optimization where we might take a fraction of an item, the 0/1 restriction forces an all-or-nothing choice. This turns our packing problem into a search through a tree of subsets, where each node represents a running total of weight and value.
To model this systematically, we define our subproblem not by whether we finish the whole bag at once, but by examining smaller sub-capacities from 0 up to 5. Let represent the maximum value we can achieve given an exact capacity limit . As we consider each item one by one, our available capacity acts as a tight boundary. If we look at item 3 (), we cannot even place it into a sub-capacity of . But at , we have two competing futures: either we skip item 3 and keep whatever best value we built with a capacity of 5, or we include item 3, gain its 12 value, and look back at what best value we could have achieved with the remaining capacity of .
This recursive relationship forces us to respect the exact order of states so we never accidentally count an item twice. If we loop forward through capacities, a single item's value might propagate multiple times into the same calculation, turning our 0/1 knapsack into an unbounded knapsack. By building our model around backwards iteration from down to , we guarantee that each item is evaluated against the clean state of the knapsack before that item was considered.
As we evaluate this transition across all three items for our capacity limit of 5, we transition from simple guesswork to a structured table of maximum possible values for every intermediate weight.
0/1 Knapsack State Space & DP Transition (W = 5) Available Items Item 1: w=1, v=6 (All-or-Nothing) Item 2: w=2, v=10 Item 3: w=3, v=12 Core DP Recurrence (Backward Iteration) DP[c] = max( DP[c], DP[c - w_i] + v_i ) Evaluating Item 3 (w=3, v=12) at Capacity c = 5 Current State Capacity c = 5 Skip Item 3 Keep Best Value at c=5 (Carry forward) Include Item 3 Add v₃(12) + Best Value at (5 - 3 = 2) DP Table State Progression across Capacities (0 to 5) c = 0 Base: 0 No items fit Max Val: 0 c = 1 Item 1 fits (w=1) Value: 6 Max Val: 6 c = 2 Item 2 fits (w=2) Value: 10 Max Val: 10 c = 3 Item 1+2 or Item 3 Values: 16 vs 12 Max Val: 16 c = 4 Optimal subset Combine w=1 & w=3 Max Val: 18 c = 5 (Max Capacity) Items 2+3 (w=5) Value: 10 + 12 = 22 Optimal: 22
Building the Core Mental Model for Resource Allocation diagram
Worked example

Tracing the DP Table: Step-by-Step Execution on Capacity 5

Phase 3: Stepping Through the Dynamic Programming Table

Now that we have established our binary choice framework, let us execute the algorithm manually on our locked example: items with weights , values , and capacity . We initialize a 1D dynamic programming array of size 6 (capacities 0 through 5), all set to 0:
python
dp = [0, 0, 0, 0, 0, 0]

Step 1: Processing Item 1 (Weight 1, Value 6)

We iterate backward from capacity 5 down to 1. For each capacity c, we test whether including Item 1 improves our maximum value:
- :
- :
- :
- :
- :
Our array updates to [0, 6, 6, 6, 6, 6].

Step 2: Processing Item 2 (Weight 2, Value 10)

We iterate backward from capacity 5 down to 2:
- :
- :
- :
- :
Our array updates to [0, 6, 10, 16, 16, 16].

Step 3: Processing Item 3 (Weight 3, Value 12)

We iterate backward from capacity 5 down to 3:
- :
- :
- :
Our final DP array is [0, 6, 10, 16, 18, 22]. Inspecting index 5 reveals our expected maximum value of 22, corresponding to Item 2 and Item 3.
python
def knapsack_trace():
    weights = [1, 2, 3]
    values = [6, 10, 12]
    W = 5
    dp = [0] * (W + 1)
    # What is the exact state of 'dp' after processing Item 3?
    return dp
Tracing the 1D DP Table (W = 5) Backward iteration over capacity 5 down to 1 Items: Item 1: W=1, V=6 Item 2: W=2, V=10 Item 3: W=3, V=12 Target Capacity: W = 5 DP Array Evolution (Capacities 0 to 5) Capacity c: c = 0 c = 1 c = 2 c = 3 c = 4 c = 5 (Ans) After Item 1: 0 6 6 6 6 6 After Item 2: 0 6 10 16 16 16 After Item 3: 0 6 10 16 18 22 Max Value at W = 5 dp = [0, 6, 10, 16, 18, 22] Backward iteration prevents item reuse
Tracing the DP Table: Step-by-Step Execution on Capacity 5 diagram
Practice

Predicting the DP Update When a Heavier Item is Introduced

Phase 4:

Now that you have traced the 1D DP table for our base items [1, 2, 3] with values [6, 10, 12] up to capacity , let us test your mechanics with a slight mutation. Imagine we introduce a fourth item: weight 4 with value 18. In the classic 0/1 knapsack setup, your inner capacity loop must iterate backwards from down to the item's weight to prevent multiple inclusions of the same item.
Consider the moment we process this new fourth item against our existing table state. Without writing out the entire code execution, apply the recurrence relation for capacity . Predict how the value at updates and explain what combination of items yields this new maximum value.
Apply

Transferring the 0/1 Knapsack Pattern to Partition Problems

Phase 5: Transfer

Now that you have traced weights and values up to capacity , you can recognize this exact capacity-budget recurrence in other combinatorial domains. The 0/1 knapsack pattern is not just about physical items and backpacks; it models any finite-resource allocation where choices are binary (include or exclude) and the objective is to maximize value without exceeding a hard limit. Consider a project funding scenario where you must select a subset of initiatives to fund without exceeding your capital limit. Instead of weights and values, you have costs and expected revenue. By adapting our 1D DP table formulation, you can solve these parallel problems without rewriting the core engine.
To test this transfer, consider a modified variant of our working example. Suppose your capacity remains , but your items have weights and values , and you must choose a subset that does not exceed capacity while maximizing total value. Using the same backward inner loop logic you practiced in the previous phases, what is the maximum attainable value, and which items are included?
Try this: Given items with weights [2, 3, 4] and values [3, 4, 5], and a capacity W = 5:
1.Initialize dp array of size 6 with zeros.
2.Iterate through each item, and for each capacity from W down to item weight, update dp[cap] = max(dp[cap], dp[cap - w] + v).
3.Determine the final maximum value at dp[5].

FAQ

Why does the greedy approach fail for the 0/1 knapsack problem?
Greedy algorithms sort items by value-to-weight ratio and pick the highest first. However, this often leaves unused capacity that could have yielded a higher total value if a different combination of items were chosen.
How does the DP table evaluate our example with weights [1,2,3], values [6,10,12], and W=5?
The DP table evaluates each item incrementally across capacities from 0 to 5. For item 3 (weight 3, value 12) with remaining capacity 2, it combines with item 2 (weight 2, value 10) to reach the maximum value of 22.
What is the time and space complexity of the 0/1 knapsack DP solution?
The standard tabulation approach has a time and space complexity of O(N * W), where N is the number of items and W is the maximum capacity. Space can be optimized to O(W) by keeping only the previous row.
Can items be fractional or reused in the 0/1 knapsack problem?
No. In 0/1 knapsack, items are indivisible (you take them or leave them) and can only be used once. Fractional reuse belongs to the Fractional Knapsack problem, which is solvable with a greedy approach.

Keep learning