---
title: "Dynamic Programming"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 23
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/23-dynamic-programming
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 23 — Dynamic Programming

Type `catlaogue` into a search box and it offers `catalogue`. To do that, the program needs a measure of how far one word is from another: the fewest letters to insert, delete or change. Trying every sequence of edits is hopeless, yet the answer comes in a table of a few hundred cells, filled in a fraction of a millisecond. The table is the method of this chapter: when a problem’s optimal solutions are made of optimal solutions of smaller problems, and the same smaller problems come back again and again, solve each one once and write the answer down.

**You already know.**

Recurrences and their costs were studied in [Chapter 13](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#ch-b1-asymptotic-analysis); [divide and conquer](https://one-course.com/books/computer-science/3/en/chapter/21-divide-and-conquer#def-b1-divide-and-conquer-dc) ([Definition 21.1](https://one-course.com/books/computer-science/3/en/chapter/21-divide-and-conquer#def-b1-divide-and-conquer-dc)) cuts a problem into independent subproblems. The second book computed Fibonacci numbers and a [longest common subsequence](#def-b1-dynamic-programming-lcs) with a table.

## 23.1 Optimal substructure and overlapping subproblems

**Definition 23.1 (Dynamic programming, optimal substructure, overlapping subproblems).**

A problem has *optimal substructure* when an optimal solution of an instance is made of optimal solutions of smaller instances, its *subproblems*. It has *overlapping subproblems* when a recursive solution meets the same subproblems many times. *Dynamic programming* solves such a problem by computing the answer of each subproblem once, from the answers of smaller ones, and storing it.

[Optimal substructure](#def-b1-dynamic-programming-dp) is proved by *cut and paste*: if the part of an optimal solution that solves a subproblem were not optimal for it, cutting it out and pasting in a better one would improve the whole, a contradiction. [Divide and conquer](https://one-course.com/books/computer-science/3/en/chapter/21-divide-and-conquer#def-b1-divide-and-conquer-dc) has [optimal substructure](#def-b1-dynamic-programming-dp) too, but its subproblems do not overlap; the Fibonacci recursion shows what overlap costs.

**Definition 23.2 (Memoisation, bottom-up evaluation).**

*Memoisation* keeps the recursive program and stores each result in a table, the memo, read before computing. *Bottom-up evaluation* fills the table in an order where every entry is computed after the entries it needs, without recursion.

```python
def fib_naive(n):
    global calls
    calls += 1
    return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)
def fib_memo(n, memo=None):
    global calls
    calls += 1
    if memo is None:
        memo = {}
    if n < 2:
        return n
    if n not in memo:  # each subproblem is solved once, then read from the table
        memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
    return memo[n]


def fib_table(n):
    """Bottom-up: the table filled in increasing order, two cells kept."""
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a
```

***Listing 23.1.** Fibonacci numbers: naive, memoised and bottom-up code/bachelor-1/23-dynamic-programming/listings/fib_memo.py*

```
$ python fib_memo.py
  n    F(n)  naive calls  memoised calls
  5       5           15               9
 10      55          177              19
 15     610         1973              29
 20    6765        21891              39
 25   75025       242785              49
```

***Output 23.1.** Calls made for $F(n)$.*

The naive recursion makes $2F(n + 1) - 1$ calls, exponential in $n$; the memoised one $2n - 1$, since each value is computed once and read once more. The bottom-up version needs neither the calls nor the table, only the last two values. The name of the method goes back to Bellman’s book *Dynamic Programming* of 1957, where “programming” means planning, as in a programme of events.

## 23.2 The recurrence first, the table second

**Method 23.3 (Designing a dynamic programme).**

1. Choose the subproblems, usually prefixes, intervals or prefixes with a budget, and give each a name with indices.
2. Write the recurrence that gives a subproblem’s answer from smaller ones, and prove it, by cut and paste.
3. Fix an order of evaluation in which every entry comes after those it reads.
4. Read the answer in the table.
5. Rebuild a solution, not just its value, by walking back through the choices that gave each entry.

**Definition 23.4 (Edit distance, alignment).**

The *edit distance* $d(a, b)$ of two words is the smallest number of single-letter insertions, deletions and substitutions that turn $a$ into $b$. An *alignment* of $a$ and $b$ writes them one above the other with gaps (written `-`), so that no column holds two gaps; its cost is the number of columns whose two entries differ.

An [alignment](#def-b1-dynamic-programming-edit) is a sequence of edits read column by column: a letter over a gap is a deletion, a gap over a letter an insertion, two different letters a substitution. So $d(a, b)$ is the smallest cost of an [alignment](#def-b1-dynamic-programming-edit) ([Exercise 23.9](#exo-b1-dynamic-programming-9)).

**Proposition 23.5 (The edit-distance recurrence).**

Let $D(i, j)$ be the [edit distance](#def-b1-dynamic-programming-edit) of the prefixes $a[{:}i]$ and $b[{:}j]$. Then $D(i, 0) = i$, $D(0, j) = j$, and for $i, j \geq 1$

$$
D(i, j) = \min\bigl(D(i - 1, j) + 1,\; D(i, j - 1) + 1,\; D(i - 1, j - 1) + [a_{i-1} \neq b_{j-1}]\bigr),
$$

where $[P]$ is 1 if $P$ holds and 0 otherwise.

**Proof.** An [alignment](#def-b1-dynamic-programming-edit) of $a[{:}i]$ with the empty word has $i$ columns, each a letter over a gap; likewise for $D(0, j)$. Otherwise, the last column of an optimal [alignment](#def-b1-dynamic-programming-edit) is $a_{i-1}$ over a gap, a gap over $b_{j-1}$, or $a_{i-1}$ over $b_{j-1}$. Removing it leaves an [alignment](#def-b1-dynamic-programming-edit) of $a[{:}i - 1]$ with $b[{:}j]$, of $a[{:}i]$ with $b[{:}j - 1]$, or of $a[{:}i
- 1]$ with $b[{:}j - 1]$, and that [alignment](#def-b1-dynamic-programming-edit) is optimal for its prefixes: a cheaper one, with the last column put back, would beat the optimal [alignment](#def-b1-dynamic-programming-edit) (cut and paste). So $D(i, j)$ is one of the three expressions, and it is at most each of them, since each is the cost of some [alignment](#def-b1-dynamic-programming-edit). ∎

```python
def table(a, b):
    """d[i][j]: the edit distance of a[:i] and b[:j]."""
    d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(len(a) + 1):
        d[i][0] = i  # delete the i letters
    for j in range(len(b) + 1):
        d[0][j] = j  # insert the j letters
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            d[i][j] = min(d[i - 1][j] + 1,  # delete a[i-1]
                          d[i][j - 1] + 1,  # insert b[j-1]
                          d[i - 1][j - 1] + (a[i - 1] != b[j - 1]))  # keep or change
    return d


def alignment(a, b, d):
    """Walk back from the corner, following a choice that gives each cell its value."""
    i, j, top, bottom = len(a), len(b), [], []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and d[i][j] == d[i - 1][j - 1] + (a[i - 1] != b[j - 1]):
            top.append(a[i - 1])
            bottom.append(b[j - 1])
            i, j = i - 1, j - 1
        elif i > 0 and d[i][j] == d[i - 1][j] + 1:
            top.append(a[i - 1])
            bottom.append("-")
            i -= 1
        else:
            top.append("-")
            bottom.append(b[j - 1])
            j -= 1
    return "".join(reversed(top)), "".join(reversed(bottom))
```

***Listing 23.2.** The table of [edit distances](#def-b1-dynamic-programming-edit), and an optimal [alignment](#def-b1-dynamic-programming-edit) rebuilt from it code/bachelor-1/23-dynamic-programming/listings/edit_distance.py*

```
$ python edit_distance.py
        r  a  i  n  s
     0  1  2  3  4  5
  t  1  1  2  3  4  5
  r  2  1  2  3  4  5
  a  3  2  1  2  3  4
  i  4  3  2  1  2  3
  n  5  4  3  2  1  2
train -> rains: distance 2
  train-
  -rains
  *    *
catlaogue -> catalogue: distance 2
  catlaogue
  catalogue
     **
```

***Output 23.2.** The table for `train` and `rains`, and two [alignments](#def-b1-dynamic-programming-edit); stars mark the edited columns.*

![The table of , row i for a(:i) and column j for b(:j). The arrows follow the walk back from D(5, 5) = 2: each step goes to a neighbour that gives the cell its value. The path spells the alignment train- over -rains.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-programming/fig-d4fe3e6d5103.svg)

*The table of [Output 23.2](#out-b1-dynamic-programming-edit), row $i$ for $a[{:}i]$ and column $j$ for $b[{:}j]$. The arrows follow the walk back from $D(5, 5) = 2$: each step goes to a neighbour that gives the cell its value. The path spells the [alignment](#def-b1-dynamic-programming-edit) `train-` over `-rains`.*

The table has $(m + 1)(n + 1)$ cells, each computed in constant time: $\Theta(mn)$. The walk back takes at most $m + n$ steps. Where several neighbours give a cell its value, the program prefers the diagonal; another preference may give another [alignment](#def-b1-dynamic-programming-edit) of the same cost.

**Definition 23.6 (Longest common subsequence).**

A *longest common subsequence* of two words is a word of largest length that can be obtained from each by deleting letters.

With insertions and deletions only, an [alignment](#def-b1-dynamic-programming-edit) keeps exactly the letters of a common subsequence, and the distance is $m + n - 2L$, with $L$ the length of a [longest common subsequence](#def-b1-dynamic-programming-lcs) ([Exercise 23.12](#exo-b1-dynamic-programming-12)): the table of the second book is the same method with another recurrence. The distance with substitutions was introduced by Levenshtein in 1965, for codes that correct lost and added bits.

![Which cells a cell (dark) reads (light). Edit distance reads three neighbours, so rows can be filled left to right, top to bottom. The knapsack reads two cells of the row above, at the same capacity and at c - w. The matrix chain reads the cells to the left in its row and below in its column, all on shorter chains, so the table is filled diagonal by diagonal from the main diagonal (grey).](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-programming/fig-83cc03b7abaa.svg)

*Which cells a cell (dark) reads (light). [Edit distance](#def-b1-dynamic-programming-edit) reads three neighbours, so rows can be filled left to right, top to bottom. The knapsack reads two cells of the row above, at the same capacity and at $c - w$. The matrix chain reads the cells to the left in its row and below in its column, all on shorter chains, so the table is filled diagonal by diagonal from the main diagonal (grey).*

## 23.3 Matrix-chain order

**Definition 23.7 (Matrix-chain problem).**

Multiplying a $p \times q$ matrix by a $q \times r$ matrix takes $pqr$ products of numbers. The *matrix-chain problem* asks, for matrices $A_1, \dots, A_n$ of sizes $p_0 \times p_1, \dots, p_{n-1}
\times p_n$, for the order of the products that computes $A_1 \cdots A_n$ with the fewest products of numbers.

The product is the same in every order, by associativity; the cost is not. Trying every order is out of the question: their number is a Catalan number, which grows like $4^n$.

```
$ python catalan.py
 2 matrices: 1 orders; Catalan C(1) = 1
 3 matrices: 2 orders; Catalan C(2) = 2
 5 matrices: 14 orders; Catalan C(4) = 14
10 matrices: 4862 orders; Catalan C(9) = 4862
20 matrices: 1767263190 orders; Catalan C(19) = 1767263190
```

***Output 23.3.** Orders of a chain of $n$ matrices, counted by a memoised recursion on the last product.*

Let $C(i, j)$ be the cheapest cost of $A_i \cdots A_j$. The last product splits the chain at some $k$, $(A_i \cdots
A_k)(A_{k+1} \cdots A_j)$, and both parts must be computed optimally (cut and paste), so

$$
C(i, i) = 0, \qquad C(i, j) = \min_{i \leq k < j} \bigl(C(i, k) + C(k + 1, j) + p_{i-1} p_k p_j\bigr).
$$

An entry reads entries for shorter chains: the table is filled by increasing length. There are $\Theta(n^2)$ entries, each a minimum over at most $n$ splits: $\Theta(n^3)$ in all.

```python
def chain_order(dims):
    """Matrix i is dims[i] x dims[i+1]. Returns (cost table, split table)."""
    n = len(dims) - 1
    cost = [[0] * n for _ in range(n)]
    split = [[0] * n for _ in range(n)]
    for length in range(2, n + 1):  # by diagonals: shorter chains first
        for i in range(n - length + 1):
            j = i + length - 1
            cost[i][j] = None
            for k in range(i, j):  # (A_i ... A_k)(A_k+1 ... A_j)
                c = cost[i][k] + cost[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
                if cost[i][j] is None or c < cost[i][j]:
                    cost[i][j], split[i][j] = c, k
    return cost, split


def parenthesise(split, i, j):
    if i == j:
        return f"A{i + 1}"
    k = split[i][j]
    return f"({parenthesise(split, i, k)} {parenthesise(split, k + 1, j)})"
```

***Listing 23.3.** The cheapest order, by intervals of increasing length, and the parenthesisation rebuilt code/bachelor-1/23-dynamic-programming/listings/chain.py*

```
$ python chain.py
cost table (row i, column j: A_i ... A_j)
       0   4000   3000   6500   3800
              0   2000   3500   3400
                     0  12000   2800
                            0   1200
                                   0
best order: (A1 ((A2 A3) (A4 A5))) with 3800 products
left to right: 20400 products
```

***Output 23.4.** Five matrices of sizes $20 \times 5$, $5 \times 40$, $40 \times 10$, $10 \times 30$, $30 \times 4$.*

The program numbers matrices from 0: its `dims[i]` is $p_i$, and its matrix $i$ is the book’s $A_{i+1}$. The best order costs 3800 products, the left-to-right order 20 400: the order matters by a factor of five on five matrices.

## 23.4 Knapsack and longest increasing subsequence

**Definition 23.8 (0/1 knapsack, pseudo-polynomial algorithm).**

The *0/1 knapsack problem* asks, for items of integer weights $w_i$ and values $v_i$ and a capacity $W$, for a set of items of total weight at most $W$ and largest total value. An algorithm is *pseudo-polynomial* if its cost is polynomial in the numbers of the input, but not in the number of digits needed to write them.

Let $K(i, c)$ be the best value of the first $i$ items within capacity $c$. Item $i$ is left out, or, if it fits, taken with the best of the first $i - 1$ items in the remaining capacity:

$$
K(0, c) = 0, \qquad K(i, c) = \max\bigl(K(i - 1, c),\; K(i - 1, c - w_i) + v_i \text{ if } w_i \leq c\bigr).
$$

```python
def knapsack(items, capacity):
    """best[i][c]: the best value of the first i items within capacity c."""
    best = [[0] * (capacity + 1) for _ in range(len(items) + 1)]
    for i, (w, v) in enumerate(items, start=1):
        for c in range(capacity + 1):
            best[i][c] = best[i - 1][c]  # without item i
            if w <= c:
                best[i][c] = max(best[i][c], best[i - 1][c - w] + v)  # with it
    return best


def chosen(items, best, capacity):
    """Walk back: item i was taken where the value changed from row i - 1."""
    take, c = [], capacity
    for i in range(len(items), 0, -1):
        if best[i][c] != best[i - 1][c]:
            take.append(i - 1)
            c -= items[i - 1][0]
    return sorted(take)
```

***Listing 23.4.** The knapsack table, and the items rebuilt from it code/bachelor-1/23-dynamic-programming/listings/knapsack.py*

```
$ python knapsack.py
capacity:   0   1   2   3   4   5   6   7   8
     none   0   0   0   0   0   0   0   0   0
 +(3, 25)   0   0   0  25  25  25  25  25  25
 +(4, 40)   0   0   0  25  40  40  40  65  65
 +(2, 15)   0   0  15  25  40  40  55  65  65
 +(5, 50)   0   0  15  25  40  50  55  65  75
  +(1, 8)   0   8  15  25  40  50  58  65  75
take items [0, 3] value 75
40 random items, capacity 737: best 1406, 30258 cells
```

***Output 23.5.** A table for five items and capacity 8; and 40 random items.*

The cost is $\Theta(nW)$. That looks polynomial, but $W$ is written with about $\log_2 W$ bits: doubling the number of bits of the capacity squares the work. With 40 items the table has 30 258 cells where the tree of [Chapter 20](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#ch-b1-backtracking) has $2^{40}$ leaves; with capacities of a hundred billion it would be the tree’s turn. Counting subsets with a given total is the same table with sums of counts instead of maxima of values: the reading lists of Chapters [20](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#ch-b1-backtracking) and [21](https://one-course.com/books/computer-science/3/en/chapter/21-divide-and-conquer#ch-b1-divide-and-conquer), now for all 80 books.

```python
def count(values, target):
    """ways[t]: the number of subsets of the values seen so far with total t."""
    ways = [1] + [0] * target
    for v in values:
        for t in range(target, v - 1, -1):  # downwards: each value used at most once
            ways[t] += ways[t - v]
    return ways[target]
```

***Listing 23.5.** Counting subsets by their total, one row code/bachelor-1/23-dynamic-programming/listings/subset_sum_dp.py*

```
$ python subset_sum_dp.py
first 16 books:            9 lists of 1000 pages, 16016 cell updates at most
first 24 books:           31 lists of 1000 pages, 24024 cell updates at most
first 40 books:          459 lists of 1000 pages, 40040 cell updates at most
first 80 books:       165521 lists of 1000 pages, 80080 cell updates at most
```

***Output 23.6.** Reading lists of 1000 pages; the counts for 16, 24 and 40 books are those of the earlier chapters.*

The loop over totals goes downwards so that `ways[t - v]` still counts the subsets without $v$; [Exercise 23.5](#exo-b1-dynamic-programming-5) shows what going upwards does.

**Definition 23.9 (Longest increasing subsequence).**

A *longest increasing subsequence* of a sequence is a subsequence, its terms taken in their order but not necessarily adjacent, that is strictly increasing and of largest length.

With $L(i)$ the length of the [longest increasing subsequence](#def-b1-dynamic-programming-lis) ending at term $i$, $L(i) = 1 + \max\{L(j) : j < i, a_j <
a_i\}$ (the maximum of an empty set being 0): $\Theta(n^2)$. A different invariant gives $\Theta(n \log n)$.

```python
def lis_table(a):
    """length[i]: the longest strictly increasing subsequence ending at a[i]."""
    length, before = [1] * len(a), [None] * len(a)
    for i in range(len(a)):
        for j in range(i):
            if a[j] < a[i] and length[j] + 1 > length[i]:
                length[i], before[i] = length[j] + 1, j
    if not a:
        return []
    i = max(range(len(a)), key=lambda k: length[k])
    out = []
    while i is not None:  # rebuild by following the predecessors
        out.append(a[i])
        i = before[i]
    return out[::-1]


def lis_patience(a):
    """The length: tops[k] is the smallest last key of an increasing subsequence of
    length k + 1 seen so far; each key goes on the leftmost pile whose top is >= it."""
    tops = []
    for x in a:
        k = bisect_left(tops, x)
        if k == len(tops):
            tops.append(x)  # a new pile on the right
        else:
            tops[k] = x
    return len(tops)
```

***Listing 23.6.** The [longest increasing subsequence](#def-b1-dynamic-programming-lis): the table, and the piles code/bachelor-1/23-dynamic-programming/listings/lis.py*

**Proposition 23.10 (Patience piles).**

After reading the first terms of $a$, `tops[k]` is the smallest last term of an increasing subsequence of length $k + 1$ among them, and `tops` is increasing. So its length at the end is the length of a [longest increasing subsequence](#def-b1-dynamic-programming-lis).

**Proof.** True before any term. Suppose it holds and the term $x$ is read. Every increasing subsequence ending at $x$ extends one whose last term is less than $x$; the longest such has length $k$, where $k$ is the number of tops less than $x$, which `bisect_left` returns. So $x$ ends an increasing subsequence of length $k + 1$ and no longer one. If $k$ is the length of `tops`, $x$ is larger than all tops and is appended: a new, longer subsequence. Otherwise $x \leq
\texttt{tops[k]}$ and $x$ replaces it, the new smallest last term for length $k + 1$; the other entries do not change, since $x$ ends no subsequence of another length that would improve them. In both cases `tops` stays increasing, as $\texttt{tops}[k - 1] < x$. ∎

```
$ python lis.py
[5, 2, 8, 6, 3, 6, 9, 7, 4, 10] -> [2, 3, 6, 9, 10] length 5
years of the 80 books in catalogue order: longest increasing subsequence 15, patience 15
  [1950, 1957, 1961, 1966, 1973, 1980, 1993, 1994, 1995, 1999, 2001, 2003, 2009, 2016, 2022]
```

***Output 23.7.** A ten-term example, and the years of publication of the catalogue’s books.*

![Patience piles for 5, 2, 8, 6, 3, 6, 9, 7, 4, 10: each pile grows upwards and never increases from bottom to top. The number of piles is the length of a longest increasing subsequence.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-programming/fig-d98c7e7e8380.svg)

*Patience piles for $5, 2, 8, 6, 3, 6, 9, 7, 4, 10$: each pile grows upwards and never increases from bottom to top. The number of piles is the length of a [longest increasing subsequence](#def-b1-dynamic-programming-lis).*

## 23.5 Saving space

A row of the edit-distance table reads only the row above it: two rows suffice for the distance.

```python
def distance(a, b):
    previous = list(range(len(b) + 1))  # row 0 of the table
    for i in range(1, len(a) + 1):
        current = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            current[j] = min(previous[j] + 1, current[j - 1] + 1,
                             previous[j - 1] + (a[i - 1] != b[j - 1]))
        previous = current  # row i - 1 is no longer needed
    return previous[-1]
```

***Listing 23.7.** The [edit distance](#def-b1-dynamic-programming-edit) with two rows code/bachelor-1/23-dynamic-programming/listings/edit_two_rows.py*

```
$ python edit_two_rows.py
distance 7 (full table: 7)
cells kept: full table 1258, two rows 68
```

***Output 23.8.** Two sentences: the same distance with 68 cells instead of 1258.*

The price is the [alignment](#def-b1-dynamic-programming-edit): the walk back needs the whole table. Hirschberg showed in 1975 how to recover it in linear space anyway, by [divide and conquer](https://one-course.com/books/computer-science/3/en/chapter/21-divide-and-conquer#def-b1-divide-and-conquer-dc): compute the middle row of the table from the top with two rows, the same from the bottom on the reversed words, find where an optimal [alignment](#def-b1-dynamic-programming-edit) crosses the middle row, and recurse on the two halves. The time stays $\Theta(mn)$, about twice as much.

## 23.6 Exercises

**Exercise 23.1 ★.**

Fill the edit-distance table of `loan` and `lane`, and give an optimal [alignment](#def-b1-dynamic-programming-edit).

**Solution of Exercise 23.1.**

Rows for the prefixes of `loan`, columns for those of `lane`:

|  |  | l | a | n | e |
| --- | --- | --- | --- | --- | --- |
|  | 0 | 1 | 2 | 3 | 4 |
| l | 1 | 0 | 1 | 2 | 3 |
| o | 2 | 1 | 1 | 2 | 3 |
| a | 3 | 2 | 1 | 2 | 3 |
| n | 4 | 3 | 2 | 1 | 2 |

The distance is 2: `loan-` over `l-ane`, deleting `o` and inserting `e`.

**Exercise 23.2 ★.**

How many calls do `fib_naive(6)` and `fib_memo(6)` make?

**Solution of Exercise 23.2.**

`fib_naive(6)` makes $2F(7) - 1 = 25$ calls, `fib_memo(6)` makes $2 \cdot 6 - 1 = 11$: one call for each $n$ from 6 down to 2 that computes, plus one call for each value read back or below 2.

**Exercise 23.3 ★.**

Add a sixth item of weight 3 and value 30 to the knapsack of [Output 23.5](#out-b1-dynamic-programming-knapsack): compute the new row, and the items taken.

**Solution of Exercise 23.3.**

From the last row $0, 8, 15, 25, 40, 50, 58, 65, 75$, the new entry for capacity $c$ is the larger of the old one and 30 plus the old one at $c - 3$: $0, 8, 15, 30, 40, 50, 58, 70, 80$. The best value is 80, with the items of weights 5 and 3 (values 50 and 30).

**Exercise 23.4 ★.**

Find the length of a [longest increasing subsequence](#def-b1-dynamic-programming-lis) of $3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5$ with the piles, and one such subsequence.

**Solution of Exercise 23.4.**

Tops after each term: $3$; $1$; $1, 4$; $1, 4$; $1, 4, 5$; $1, 4, 5, 9$; $1, 2, 5, 9$; $1, 2, 5, 6$; $1, 2, 5, 6$; $1, 2,
3, 6$; $1, 2, 3, 5$. Four piles: length 4, for instance $1, 4, 5, 9$ or $1, 2, 3, 5$.

**Exercise 23.5 ★★.**

The one-row knapsack below goes through the capacities upwards or downwards. Explain the two results.

```python
def one_row(items, capacity, downwards):
    best = [0] * (capacity + 1)
    for w, v in items:
        order = range(capacity, w - 1, -1) if downwards else range(w, capacity + 1)
        for c in order:
            best[c] = max(best[c], best[c - w] + v)
    return best[capacity]
```

***Listing 23.8.** The knapsack on one row code/bachelor-1/23-dynamic-programming/listings/exo_knapsack_up.py*

```
downwards: 65  upwards: 80
```

***Output 23.9.** Items $(3, 25)$, $(4, 40)$, $(2, 15)$, capacity 8. Some lines are left out.*

**Solution of Exercise 23.5.**

Downwards, `best[c - w]` has not yet been updated for the current item: it is the best value without it, and each item is used at most once, which gives 65. Upwards, `best[c - w]` may already contain the current item, which is then taken again: 80 is twice the item $(4, 40)$. That is the right method for a knapsack with unlimited copies of each item, the wrong one here.

**Exercise 23.6 ★★.**

This memo is keyed on the identity of the list of values, which the recursion shortens and restores. Explain the wrong counts and repair the key.

```python
def ways(values, target):
    """Subsets of values with the given total; values is shortened and restored."""
    key = (id(values), target)
    if key in memo:
        return memo[key]
    if not values:
        result = int(target == 0)
    else:
        v = values.pop()  # decide the last value, then put it back
        result = ways(values, target) + ways(values, target - v)
        values.append(v)
    memo[key] = result
    return result
```

***Listing 23.9.** A memo keyed on a list code/bachelor-1/23-dynamic-programming/listings/exo_memo_mutable.py*

```
total 10: memoised 2, all 32 subsets 2
total 13: memoised 0, all 32 subsets 2
total 17: memoised 0, all 32 subsets 2
```

***Output 23.10.** Against all subsets. Some lines are left out.*

**Solution of Exercise 23.6.**

The recursion always passes the same list object, shortened, so `id(values)` is the same at every depth: the result for a prefix of three values is stored under the same key as the result for five, and read back in place of it. For the total 10 the confusion happens to give the right count; for 13 and 17 it does not. The subproblem is a prefix and a total, so the key should say which prefix: `(len(values), target)`, or `(tuple(values), target)`, which costs a copy.

**Exercise 23.7 ★★.**

Talks $[s, f)$ now have weights. Find a set of compatible talks of largest total weight in $O(n \log n)$; the greedy rule of [Theorem 22.4](https://one-course.com/books/computer-science/3/en/chapter/22-greedy-algorithms-and-their-proofs#thm-b1-greedy-proofs-earliest-finish) no longer works.

**Solution of Exercise 23.7.**

```python
def best_weight(talks):
    """talks: (start, end, weight). best[i]: the best of the first i talks by end."""
    talks = sorted(talks, key=lambda t: t[1])
    ends = [t[1] for t in talks]
    best = [0] * (len(talks) + 1)
    for i, (s, _, w) in enumerate(talks, start=1):
        p = bisect_right(ends, s, 0, i - 1)  # talks ending at or before s
        best[i] = max(best[i - 1], best[p] + w)  # without talk i, or with it
    return best[-1]
```

*Weighted interval scheduling code/bachelor-1/23-dynamic-programming/exercises/weighted_intervals.py*

Sort the talks by finishing time; let $B(i)$ be the best weight using the first $i$, and $p(i)$ the number of talks among the first $i - 1$ that finish by the start of talk $i$. An optimal set either leaves talk $i$ out, or takes it together with an optimal set of the $p(i)$ talks compatible with it: $B(i) = \max(B(i - 1), B(p(i)) + w_i)$. Sorting and the binary searches cost $O(n \log n)$. A heavy talk overlapping two light compatible ones defeats the earliest-finish rule.

**Exercise 23.8 ★★.**

In how many ways can one climb $n$ stairs with steps of sizes taken from a given set, the order of the steps counting?

**Solution of Exercise 23.8.**

```python
def climbs(n, steps):
    ways = [1] + [0] * n  # ways[k]: ordered sequences of steps summing to k
    for k in range(1, n + 1):
        ways[k] = sum(ways[k - s] for s in steps if s <= k)
    return ways[n]
```

*Ways to climb code/bachelor-1/23-dynamic-programming/exercises/stairs.py*

The last step of a climb to $k$ has some size $s$, and before it comes any climb to $k - s$: $W(k) = \sum_{s \leq k}
W(k - s)$ with $W(0) = 1$, in $O(n \cdot |S|)$. With steps 1 and 2, $W(n)$ is the Fibonacci number $F(n + 1)$: 89 for $n = 10$.

**Exercise 23.9 ★★.**

Show that the [edit distance](#def-b1-dynamic-programming-edit) equals the smallest cost of an [alignment](#def-b1-dynamic-programming-edit).

**Solution of Exercise 23.9.**

An [alignment](#def-b1-dynamic-programming-edit) of cost $c$ is read as $c$ edits, column by column, so $d(a, b)$ is at most the smallest cost. Conversely, take $d$ edits turning $a$ into $b$. Edits never reorder letters: the letters of $a$ that survive, perhaps changed, end at positions of $b$ in the same order. Write each over its final letter, the deleted letters of $a$ over gaps and the other letters of $b$ under gaps. A column of two different letters needs at least one substitution of that letter, a column with a gap at least one deletion or insertion, all different edits: the [alignment](#def-b1-dynamic-programming-edit) costs at most $d$.

**Exercise 23.10 ★★★.**

Show another way that the number of patience piles is the length of a [longest increasing subsequence](#def-b1-dynamic-programming-lis): each pile never increases from bottom to top, and each key placed on pile $k > 0$ has a smaller key on pile $k - 1$ placed before it.

**Solution of Exercise 23.10.**

A key goes on a pile only if its top is not smaller, so each pile never increases from bottom to top; the keys of one pile came in that order, so an increasing subsequence takes at most one key from each pile, and its length is at most the number of piles. When a key $x$ goes on pile $k > 0$, the top $y$ of pile $k - 1$ is less than $x$ and came before it; remember $y$. From any key on the last pile, following these remembered keys back to pile 0 gives keys that increase and come in order, one per pile: an increasing subsequence as long as the number of piles.

**Exercise 23.11 ★★★.**

Compute the length of a longest subsequence of a word that is a palindrome, in $O(n^2)$, and test it.

**Solution of Exercise 23.11.**

```python
def longest_palindrome(s):
    n = len(s)
    if n == 0:
        return 0
    best = [[0] * n for _ in range(n)]  # best[i][j]: for s[i..j]
    for i in range(n - 1, -1, -1):
        best[i][i] = 1
        for j in range(i + 1, n):
            if s[i] == s[j]:
                best[i][j] = best[i + 1][j - 1] + 2 if j > i + 1 else 2
            else:
                best[i][j] = max(best[i + 1][j], best[i][j - 1])
    return best[0][n - 1]
```

*The longest palindromic subsequence code/bachelor-1/23-dynamic-programming/exercises/palindrome.py*

For $s[i..j]$: if the end letters are equal, a best palindrome may use both around a best one of $s[i + 1..j - 1]$; otherwise it does without one of them. Cells are filled for $i$ decreasing and $j$ increasing, so each reads cells already computed: $\Theta(n^2)$. The test compares with all subsequences of random words of up to 10 letters.

**Exercise 23.12 ★★★.**

With insertions and deletions only, show that the distance of $a$ and $b$ is $m + n - 2L$, where $m$, $n$ are their lengths and $L$ the length of a [longest common subsequence](#def-b1-dynamic-programming-lcs).

**Solution of Exercise 23.12.**

Without substitutions, every column of an [alignment](#def-b1-dynamic-programming-edit) of finite cost holds two equal letters, or a letter and a gap. The columns of equal letters spell a common subsequence of some length $M$; the other $m - M$ letters of $a$ and $n - M$ of $b$ face gaps. So the cost is $m + n - 2M$, smallest when $M$ is the length $L$ of a [longest common subsequence](#def-b1-dynamic-programming-lcs), and by [Exercise 23.9](#exo-b1-dynamic-programming-9) the distance is $m + n - 2L$.

## 23.7 Problem: A spelling checker for the catalogue

**Problem 23.1.**

Weekend problem — A spelling checker for the catalogue

Eight misspelt queries are matched against the 80 titles of the catalogue, in lower case. The program computes [edit distances](#def-b1-dynamic-programming-edit) with two rows, and avoids most of them with the triangle inequality: four titles serve as *pivots*, whose distances to every title are computed once.

```python
def nearest_pruned(query, books, pivots, to_pivot):
    """to_pivot[t][k] = distance(t, pivots[k]), computed once for the catalogue.
    By the triangle inequality, |d(q, p) - d(p, t)| <= d(q, t) for every pivot p."""
    computed = len(pivots)
    dq = [distance(query, p) for p in pivots]
    bound = {t: max(abs(x - y) for x, y in zip(dq, to_pivot[t])) for t in books}
    best = (float("inf"), None)
    for t in sorted(books, key=lambda t: bound[t]):  # most promising first
        if bound[t] >= best[0]:
            break  # every remaining title is at least as far as the best found
        best = min(best, (distance(query, t), t))
        computed += 1
    return best, computed
```

***Listing 23.10.** The nearest title, with [pruning](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-pruning) code/bachelor-1/23-dynamic-programming/listings/spell.py*

```
$ python spell.py
'the clokwork harbor'      -> 'the clockwork harbour'    distance 2,  5 distances computed
'a map of the lighthose'   -> 'a map of the lighthouse'  distance 1,  5 distances computed
'notes on the libary'      -> 'notes on the library'     distance 1,  5 distances computed
'the silent comit'         -> 'the silent comet'         distance 1,  5 distances computed
'beyond the rivr'          -> 'beyond the river'         distance 1,  7 distances computed
'under the gardn'          -> 'under the garden'         distance 1,  5 distances computed
'seven machnie'            -> 'seven machine'            distance 2,  6 distances computed
'the hiden kingdom'        -> 'the hidden kingdom'       distance 1,  7 distances computed
pruned: 45 distances for 8 queries; brute force: 640
```

***Output 23.11.** Eight queries, their nearest titles, and the distances computed.*

**Part I — The recurrence and its table.**

1. Why is the distance of `the silent comit` and `the silent comet` equal to 1?
2. How many cells has the table of a query of 19 characters against a title of 21?
3. In which order are the cells filled, and why is every cell read after it is computed?
4. What is the cost of one distance computation for words of lengths $m$ and $n$ ?
5. How many distances does a brute-force search compute per query?
6. Why is $D(i, 0) = i$ ?

**Part II — Alignments.**

7. Give an optimal [alignment](#def-b1-dynamic-programming-edit) of `the clokwork harbor` with `the clockwork harbour` .
8. Give two optimal [alignments](#def-b1-dynamic-programming-edit) of `catlaogue` and `catalogue` .
9. Why does the walk back always find a neighbour that gives the cell its value?
10. What is the cost of the walk back?
11. Why does the two-row version lose the [alignment](#def-b1-dynamic-programming-edit) ?
12. Describe how the [alignment](#def-b1-dynamic-programming-edit) can still be found in linear space.

**Part III — Time and space.**

13. Read the cells kept by the full table and by two rows in [Output 23.8](#out-b1-dynamic-programming-two-rows) .
14. How many cells does each version keep for two words of 1000 letters?
15. Does saving space change the time?
16. How many distances are computed once, for the pivots?
17. How many distances do the eight queries compute, against [brute force](https://one-course.com/books/computer-science/3/en/chapter/20-exhaustive-search-and-backtracking#def-b1-backtracking-exhaustive) ?
18. From how many queries on does the computation for the pivots pay off, at this rate?

**Part IV — A metric, and pruning.**

19. Show that $d(a, b) = 0$ exactly when $a = b$ .
20. Show that $d(a, b) = d(b, a)$ .
21. Prove the triangle inequality $d(a, c) \leq d(a, b) + d(b, c)$ .
22. Deduce that $|d(q, p) - d(p, t)| \leq d(q, t)$ for any query $q$ , pivot $p$ and title $t$ .
23. Why can the loop stop at the first title whose bound is at least the best distance found?
24. State the named result, *[edit distance](#def-b1-dynamic-programming-edit) is a metric* , with the saving it brings on the catalogue.

**Solution of Problem 23.1.**

**1.** One substitution, `i` into `e`, turns one into the other, and the words differ, so the distance is not 0.

**2.** $20 \times 22 = 440$.

**3.** Row by row, each from left to right: a cell reads its left, upper and upper-left neighbours, all filled before it.

**4.** $\Theta(mn)$, a constant amount of work per cell.

**5.** 80, one per title.

**6.** Turning $i$ letters into none takes $i$ deletions, and no operation removes more than one letter.

**7.** `the clo-kwork harbo-r` over `the clockwork harbour`: two insertions.

**8.** `catlaogue` over `catalogue` (two substitutions), and `cat-laogue` over `catal-ogue` (an insertion and a deletion).

**9.** A cell’s value is the smallest of three expressions, so it equals at least one of them.

**10.** $O(m + n)$: each step lowers $i + j$ by at least 1.

**11.** The walk back reads cells of every row, and only the last two rows are kept.

**12.** Compute the middle row from the top and the same row from the bottom, on the reversed words, each with two rows; the column where their sum is smallest is where an optimal [alignment](#def-b1-dynamic-programming-edit) crosses the middle; recurse on the two halves (Hirschberg’s method).

**13.** 1258 cells against 68.

**14.** $1001^2 = 1\,002\,001$ against $2 \times 1001 = 2002$.

**15.** No: both versions compute every cell once, $\Theta(mn)$.

**16.** $4 \times 80 = 320$.

**17.** 45 against 640.

**18.** A query saves about $80 - 45/8 \approx 74$ distances, so the 320 pay off from the fifth query on.

**19.** No edit is needed exactly when the words are equal.

**20.** Each edit can be undone by one edit, an insertion by a deletion and a substitution by a substitution: the reversed sequence turns $b$ into $a$ in as many steps.

**21.** Following $d(a, b)$ edits from $a$ to $b$, then $d(b, c)$ edits from $b$ to $c$, turns $a$ into $c$; the smallest number of edits is at most that.

**22.** $d(q, p) \leq d(q, t) + d(t, p)$ gives $d(q, p) - d(p, t) \leq d(q, t)$, and $d(p, t) \leq d(p, q) + d(q, t)$ gives $d(p, t) - d(q, p) \leq d(q, t)$; for several pivots, the largest of these bounds.

**23.** The titles come by increasing bound, and each bound is at most the true distance: once a bound reaches the best distance found, every remaining title is at least that far. (A title at an equal distance may be skipped: the program returns one nearest title.)

**24.** *[Edit distance](#def-b1-dynamic-programming-edit) is a metric*: it is zero exactly on equal words, symmetric, and satisfies the triangle inequality (questions 19–21). On the catalogue, the bound it gives lets the eight queries compute 45 distances instead of 640, after 320 computed once for the pivots.
