1. Concept library
  2. Data Structures & Algorithms
  3. Module 13: Dynamic programming

Concept

Knapsack patterns

The knapsack family covers choosing items under a capacity: 0/1 (each item once), unbounded (any number of times) and subset sum. The same table, with the inner loop running in a different direction, handles each.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain the 0/1, unbounded and subset-sum variants
  2. Write the 0/1 knapsack table and trace it on three items
  3. Spot the forward inner loop that counts an item twice

In practice

A few lines that show Knapsack patterns doing its job.

Python
def knapsack_01(weights, values, capacity):
    best = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for cap in range(capacity, w - 1, -1):     # backwards: use once
            best[cap] = max(best[cap], best[cap - w] + v)
    return best[capacity]

def unbounded(weights, values, capacity):
    best = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for cap in range(w, capacity + 1):         # forwards: reuse
            best[cap] = max(best[cap], best[cap - w] + v)
    return best[capacity]

The common mistake

Watch for

Running the 0/1 inner loop forwards over capacity. Each item is then counted more than once, and you have quietly solved the unbounded problem instead.

What to know first

Your roadmap puts these before Knapsack patterns, unless you already know them.

How it stays learned

Once a session shows you understand Knapsack patterns, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Tabulation