Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Dynamic programming
EXPERIMENT 59 / 66

A budget for the best combination.

Choose items once each and update capacity states in the correct direction.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

01 Model the idea

In 0/1 knapsack, each item can be selected at most once. The objective is maximum total value without exceeding capacity. A DP state records the best value available for a capacity after considering a prefix of items. With a one-dimensional table, iterate capacities downward so the current item cannot feed another state that uses it again.

THE THING THAT MUST STAY TRUE

After an item pass, each state is optimal using only items considered so far.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
FOR each item
  VISIT capacities from high to low
  choose between skipping and taking the item once
A worked trace for this experiment
Items consideredCapacity 5 best value
None0
(2,4)4
(2,4), (3,5)9
All three items9

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

knapsack.py
def knapsack(items, capacity):
    best = [0] * (capacity + 1)
    for weight, value in items:
        if weight <= 0: raise ValueError("Positive item weights required")
        for available in range(capacity, weight - 1, -1):
            best[available] = max(best[available], best[available - weight] + value)
    return best[capacity]
print(knapsack([(2, 4), (3, 5), (4, 7)], 5))
↳ EXPECTED OUTPUT
9
  1. 1

    The item pair is weight then value. Selecting the first two items uses capacity five and produces value nine.

  2. 2

    Descending capacity order keeps best[available-weight] from already containing the same current item. Ascending order would implement a different, unbounded reuse pattern.

  3. 3

    The O(nW) bound depends on numeric capacity W, which can be exponentially large relative to its bit representation. This is called pseudo-polynomial time, not a general polynomial solution to the decision problem.

04 Count the cost

TIME

O(nW) for n items and capacity W; pseudo-polynomial

SPACE

O(W)

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Check that an item too heavy to fit contributes nothing and that capacity zero returns zero.

Reveal one possible solution +
one_possible_solution.py
def knapsack(items, capacity):
    best = [0] * (capacity + 1)
    for weight, value in items:
        for available in range(capacity, weight - 1, -1):
            best[available] = max(best[available], best[available - weight] + value)
    return best[capacity]
assert knapsack([(2, 4)], 1) == 0
assert knapsack([(2, 4)], 0) == 0
print("Capacity boundaries passed")

06 Check your reasoning

QUICK SIGNAL CHECK

Why update capacity downward for 0/1 knapsack?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.