liveBook · Manning

Knapsack problem

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

The knapsack problem is an optimization problem that selects items with given values and weights to maximize total value without exceeding a capacity limit.

The knapsack problem selects whole items with different weights and values to maximize value without exceeding a fixed capacity. In the 0/1 variant, each item is either taken once or left behind. section 8.1

Figure 8.1. The robber must carefully decide what items to steal because the capacity of the knapsack is limited.

A limited-capacity theft scenario makes the competing goals—value and available weight—immediately visible. section 8.1

Solve the problem incrementally with a dynamic-programming table:

  • Represent each item with a name, weight, and value. section 8.1
  • Treat each table cell as the best value available for a capacity and a prefix of the item list. section 8.1
  • For each item and capacity, keep the previous value when the item does not fit; otherwise compare excluding it with including it. section 8.1
  • Reconstruct the chosen items by walking backward through the table and subtracting the weight of every item whose inclusion changed the value. section 8.1

A 75-pound selection

A candidate list includes a television, candlesticks, stereo, laptop, clothing, jewelry, and other household goods. Calling knapsack(items: items, maxCapacity: 75) chooses the highest-value combination that fits, rather than testing every subset. section 8.1

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Develops a table-based dynamic-programming solution and backward reconstruction, while avoiding a full formal proof.
Examples
Uses household theft, a 75-pound item list, and a three-item table containing matches, a flashlight, and a book.
What it assumes
Assumes basic programming and relates the technique to memoization rather than teaching optimization or recursion from zero.
What you can do after
Build it from scratch with an item type, dynamic-programming table, capacity loop, and backward solution reconstruction.
How it connects
Connects dynamic programming with memoization, brute-force powersets, and resource-allocation optimization.

Also explained in

Compare how 4 books explain knapsack problem →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.