liveBook · Manning

Dynamic programming

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

Dynamic programming is an algorithmic technique that solves a problem by combining solutions to overlapping smaller subproblems, typically storing intermediate results.

Dynamic programming solves a large problem by solving overlapping smaller subproblems, storing their results, and combining them. It replaces the knapsack problem’s exponential brute-force search with a table indexed by item count and capacity. section 8.1

A table-driven knapsack solution proceeds in stages:

  • Represent each item with a name, weight, and value. section 8.1
  • Create a table whose rows represent available items and whose columns represent capacities. section 8.1
  • For each item and capacity, keep the previous best value when the item does not fit; otherwise compare skipping it with taking it. section 8.1
  • Walk backward through the completed table, detecting changed values to reconstruct the selected items and their remaining capacity. section 8.1

A constrained theft problem

Given items with different weights and values, a thief may take each item once. For a 75-pound capacity, the algorithm evaluates every item-capacity combination without enumerating every subset, then returns the most valuable feasible selection. The same pattern applies to allocating a limited athletic budget among teams with expected returns. section 8.1 section 8.5

Table 8.1. An example of a knapsack problem of three items

Weight

0

1

2

3

Matches (1 lb, $5) 0 5 5 5
Flashlight (2 lbs, $10) 0 5 10 15
Book (1 lb, $15) 0 15 20 25

A small three-item table makes the recurrence visible: each cell records the best value for a particular capacity and set of available items. section 8.1

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

How deep it goes
Explains table construction, include-or-skip choices, and backward reconstruction of the selected items.
Examples
Uses a three-item knapsack table, a 75-pound item set, and athletic-budget allocation as concrete examples.
What it assumes
Assumes familiarity with brute-force search and memoization while teaching subproblem tables through knapsack.
What you can do after
Builds a table-driven 0/1 knapsack solver and reconstructs the selected items.
How it connects
Connects dynamic programming with memoization, knapsack, resource allocation, and routing optimization.

Also explained in

Compare how 5 books explain dynamic programming →

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.