CS 351 // ANALYSIS OF ALGORITHMS

Dynamic Programming, Part 1.

Remember what you already solved: recursion, memoization, and the algorithm

Lucas P. Cordova, Ph.D.

Willamette University  |  Fall 2026

O(n²)O(n)O(log n)

Outline

  1. What is it for?
    Four questions you already know how to ask, and the one habit that answers them
  2. The Ford Hall stairs
    Counting ways: why plain recursion explodes, and the table that fixes it
  3. The algorithm
    Six questions that turn a recurrence into an algorithm
  4. Overnight stops on I-5
    A shortest path on a line, solved as a table
  5. Cutting a Douglas fir log
    Choices, a recurrence, a table, and reading the answer back
  6. Activity: The log yard
    Your turn, in pairs
  7. Wrap-up
    What to keep, and what comes next
CS 351

What you should take away today

BY THE END OF CLASS YOU CAN

  • Recognize a dynamic programming problem: a best value or a count over a sequence of choices, where the same smaller questions keep coming back.
  • Explain why plain recursion explodes on overlapping subproblems, and how a memo table or a bottom-up table brings it down to one solve per subproblem.
  • Tell apart total calls from stack depth: total calls is running time; open calls at once is the stack, and Python stops near 1,000 frames. Bottom-up has depth 1.
  • Apply the six questions (Subproblems, Relate, Order, Base cases, Original, Time) to turn a recurrence into an algorithm with a running time.
  • Fill a one-dimensional table by hand and read the answer back through the choice pointers, for the stairs, the I-5 hotels, and the log.
  • Check a dynamic program someone else wrote, including a language model, against its base cases and its own table.
CS 351
// SECTION

What is it for?

Four questions you already know how to ask, and the one habit that answers them

O(n²)O(n)O(log n)

Where you have already met it

THE USE CASE

Every one of these is a question about the best or the number of ways to make a sequence of choices. Each one is solved by the same habit: solve the small versions once, write them down, build up.

The questionThe choicesWhat dynamic programming computes
Turn-by-turn directions on one-way streetswhich street to take nextshortest path on a DAG: last week's relaxation in topological order
Autocorrect on your phoneinsert, delete, or swap a letteredit distance between what you typed and each dictionary word
Lining up two DNA sequencesmatch, skip, or gapthe best alignment score (longest common subsequence)
Your LaTeX homework PDFwhere to break each linethe paragraph with the least total badness (TeX's line breaker)
A sawmill cutting logswhere to cutthe cut pattern with the highest revenue (today)
Packing a resupply box for the PCTtake an item or leave itthe most calories under the weight limit (next week)
CS 351

When to reach for it

  • The answer is a best value (max, min), a count, or a yes/no over a sequence of choices.
  • Brute force means trying every sequence of choices: exponential.
  • A good answer to the whole problem is built from good answers to smaller versions of the same problem.
  • The smaller versions repeat: the same subproblem shows up many times in the brute-force tree.
  • There are only polynomially many distinct subproblems. Solve each once; look it up ever after.
IN ONE LINE

Dynamic programming is recursion plus a notebook. Write every answer down the first time; read it every time after.

CS 351

Last week and this week


Greedy (Dijkstra)  Dynamic programming
How it decidescommits to the locally best choice and never looks backtries every choice for the current subproblem, keeps the best
Why it is righta proof that the local choice is safe (cut property, non-negative edges)the recurrence itself: every option was considered
When it worksthe problem has a safe greedy choice (rare, and you must prove it)subproblems repeat and the best answer is built from best sub-answers
Costusually near-linearnumber of subproblems times work per subproblem; polynomial
ExampleMST, shortest paths with non-negative weightsstairs, road trip, log cutting (today); edit distance, knapsack (next)
CS 351

[🙈             vs.             🧠]

// SECTION

The Ford Hall stairs

Counting ways: why plain recursion explodes, and the table that fixes it

Climbing the Ford Hall stairs

THE USE CASE

The stairs up to Ford 102 have n steps. You climb one or two steps at a time. How many different ways are there to reach the top?

  • Your last move was either one step (from step n − 1) or two steps (from step n − 2).
  • So ways(n) = ways(n − 1) + ways(n − 2).
  • ways(0) = 1 (you are already there), ways(1) = 1.
  • ways(6) = 13. Those are the Fibonacci numbers, in disguise.
123456

THE LAST MOVE INTO STEP 6 CAME FROM STEP 5 OR STEP 4.

CS 351

Plain recursion: it works, and it explodes

def ways(steps: int) -> int:
    if steps <= 1:
        return 1
    return ways(steps - 1) + ways(steps - 2)
nways(n)calls made
61325
1089177
2010,94621,891
301,346,2692,692,537
40165,580,141331,160,281
6543210121032101432101210

THE CALL TREE OF ways(6): 25 CALLS. ways(4) IS COMPUTED TWICE, ways(3) THREE TIMES, ways(2) FIVE TIMES.

WHY

The tree doubles with every two extra steps: about 1.6ⁿ calls. ways(40) takes a few minutes; ways(80) would outlast the semester.

CS 351

💥💥💥💥💥💥💥

Memoization: write it down the first time 🧠

from functools import lru_cache

@lru_cache(maxsize=None)          # the notebook
def ways(steps: int) -> int:
    if steps <= 1:
        return 1
    return ways(steps - 1) + ways(steps - 2)

# the same thing by hand:
memo: dict[int, int] = {}
def ways_memo(steps: int) -> int:
    if steps <= 1:
        return 1
    if steps not in memo:           # first time: compute
        memo[steps] = ways_memo(steps - 1) + ways_memo(steps - 2)
    return memo[steps]              # every time: look up
65432101234

WITH A TABLE: 11 CALLS INSTEAD OF 25. AMBER = ANSWERED FROM THE TABLE.

  • Each ways(k) is computed once; every other call is a lookup.
  • n distinct subproblems, O(1) work each: O(n) time, O(n) space.
CS 351

Top-down has a ceiling: the call stack ⬇️

import sys
from functools import lru_cache

@lru_cache(maxsize=None)
def ways(steps: int) -> int:
    if steps <= 1:
        return 1
    return ways(steps - 1) + ways(steps - 2)

print(ways(40))                 # 165580141, instantly
print(sys.getrecursionlimit())  # 1000
print(ways(1500))               # RecursionError: maximum
                                # recursion depth exceeded
WHERE THE DEPTH COMES FROM

ways(1500) calls ways(1499), which calls ways(1498), and so on: 1500 calls are open before the first one returns and the first table entry is written. The table fills from the bottom of the stack up, so top-down is always as deep as the problem is long.

Try it: dp.html?mode=stairs&n=1500&variant=memo (watch the stack gauge cross the limit), then switch to bottom-up.

  • Two different counts. Total calls is time: plain ways(40) makes 331,160,281 of them. Open calls at once is the stack: plain ways(40) is never more than 40 deep, so it is slow and safe.
  • Memoization flips it. ways(1500) makes about 1,500 calls (fast) but is 1,500 deep. Python stops near 1,000: RecursionError.
  • sys.setrecursionlimit(10_000) raises the ceiling. Past a few tens of thousands of frames the interpreter itself can run out of stack and crash, so this is a patch for homework, and the real fix is on the next slide.
  • Bottom-up is a loop over the table in a safe order: the same work, depth 1, no limit to hit.
CS 351

Bottom-up: fill the table in order, no recursion ⬆️

def ways_bottom_up(steps: int) -> int:
    table = [0] * (steps + 1)
    table[0] = table[1] = 1          # base cases first
    for k in range(2, steps + 1):     # smaller before larger
        table[k] = table[k - 1] + table[k - 2]
    return table[steps]
Memoized (top-down)Bottom-up
Orderwhatever the recursion asks foryou choose: smaller subproblems first
Codethe recurrence plus a cachea loop over the table
Workonly the subproblems actually neededevery subproblem in the table
Riskrecursion depth (Python stops near 1000)none; and space can often shrink (keep two cells)
  • Both run in O(n). Both are dynamic programming.
  • Bottom-up is the recursion unrolled: the loop visits subproblems in an order where everything needed is already filled in.
  • That order is a topological order of the subproblem graph. Keep that thought for the algorithm.
CS 351

🫵🏼 Try it: the stairs, plain and with a table 

CS 351

Check the answer against an LLM 🤖

THE PROMPT

A staircase has n steps and you climb 1 or 2 at a time. Give a recurrence for the number of ways to reach the top, with base cases, and the count for 6 steps. What is the running time with and without memoization? Is the memoized version safe to call with n = 1500 in Python?

THE MODEL'S ANSWER

“The number of ways to climb n steps taking 1 or 2 at a time satisfies ways(n) = ways(n − 1) + ways(n − 2). The base cases are ways(0) = 0 and ways(1) = 1, so the sequence is 0, 1, 1, 2, 3, 5, 8: there are 8 ways to climb 6 steps. With memoization this runs in O(n) time; without memoization it also runs in O(n) time, because each value is computed from the two before it. Memoized, ways(1500) is instant and safe, since only 1,500 values are stored.”

  • Fluent, confident, and wrong in three places. Find them; you have the table and the stack from the stairs slides.
  • Base cases. ways(0) = 1: one way to climb zero steps, by standing still. The sequence is 1, 1, 2, 3, 5, 8, 13 and ways(6) = 13, the number we counted.
  • Time. Without memoization the call tree for n = 6 has 25 calls and for n = 40 about 331 million. O(n) describes the memoized version only.
  • Depth. 1,500 stored values is fine; 1,500 open calls is not. Memoized ways(1500) is 1,500 deep before the first return and Python stops near 1,000: RecursionError. Bottom-up is the safe version.
  • The six questions are a checklist for anyone's answer: yours, a classmate's, a model's. Next time we grade a longer one, and the homework asks you to grade a whole transcript.
CS 351
// SECTION

The algorithm

Six questions that turn a recurrence into an algorithm

O(n²)O(n)O(log n)

Six questions to ask, every time

AskFor the stairs
Subproblems. What smaller versions of the question will I store? How many?ways(k) = ways to climb k steps; n + 1 of them
Relate. How does one subproblem's answer come from smaller ones? (What is the last choice?)ways(k) = ways(k − 1) + ways(k − 2)
Order. Which subproblems must be done first? (A topological order of the dependencies.)increasing k
Base cases. Which subproblems have a direct answer?ways(0) = ways(1) = 1
Original. Which subproblem (or combination) answers the real question?ways(n)
Time. Subproblems × work per subproblem.(n + 1) × O(1) = O(n)
CS 351

Subproblems form a DAG

  • Draw one vertex per subproblem and an edge from each subproblem to the ones it needs.
  • Relate gives the edges. Order is a topological order of this graph. Base cases are the sources.
  • Memoization walks it by depth-first search; bottom-up walks it in topological order. Same graph, two traversals.
  • If the graph has a cycle, the recurrence is circular and there is no DP (yet): pick different subproblems.
012345

ways(k) NEEDS ways(k − 1) (GREY) AND ways(k − 2) (AMBER). SOURCES 0 AND 1 ARE THE BASE CASES.

SAME IDEA AS LAST WEEK

Shortest paths on a DAG were computed by relaxing edges in topological order. That was dynamic programming: dist[v] = min over incoming edges of dist[u] + w(u, v).

CS 351
// SECTION

Overnight stops on I-5

A shortest path on a line, solved as a table

O(n²)O(n)O(log n)

Salem to Ashland, with hotels

THE USE CASE

Driving I-5 from Salem to Ashland (236 miles) with a rule: at most 120 miles a day, then a hotel. Hotels cost different amounts in each town. Which towns do you stop in to spend the least?

Salemmile 0startEugenemile 59hotel $110Cottage Grovemile 79hotel $80Roseburgmile 129hotel $90Medfordmile 223hotel $140Ashlandmile 236destination
CS 351

The six questions for the road trip

AskAnswer
Subproblemsbest(c) = least hotel money spent to arrive in town c; one per town
Relatebest(c) = hotel(c) + min over earlier towns p within 120 miles of best(p)
Ordertowns from north to south along the road (increasing mile marker)
Base casebest(Salem) = 0
Originalbest(Ashland), with hotel(Ashland) = 0: no hotel on the night you arrive
Timen towns × up to n earlier towns = O(n²); O(n) with the range rule
CS 351

Fill the table: Eugene at mile 59

Salemmile 0start$0Eugenemile 59hotel $110$110Cottage Grovemile 79hotel $80Roseburgmile 129hotel $90Medfordmile 223hotel $140Ashlandmile 236destination
WHAT HAPPENED

Towns within 120 miles: Salem. from Salem: 0 + 110 = 110. Keep the smallest: best(Eugene) = $110, arriving from Salem.

townbestfrom
Salem$0start
Eugene$110Salem
Cottage Grove··
Roseburg··
Medford··
Ashland··
CS 351

Fill the table: Cottage Grove at mile 79

Salemmile 0start$0Eugenemile 59hotel $110$110Cottage Grovemile 79hotel $80$80Roseburgmile 129hotel $90Medfordmile 223hotel $140Ashlandmile 236destination
WHAT HAPPENED

Towns within 120 miles: Salem, Eugene. from Salem: 0 + 80 = 80; from Eugene: 110 + 80 = 190. Keep the smallest: best(Cottage Grove) = $80, arriving from Salem.

townbestfrom
Salem$0start
Eugene$110Salem
Cottage Grove$80Salem
Roseburg··
Medford··
Ashland··
CS 351

Fill the table: Roseburg at mile 129

Salemmile 0start$0Eugenemile 59hotel $110$110Cottage Grovemile 79hotel $80$80Roseburgmile 129hotel $90$170Medfordmile 223hotel $140Ashlandmile 236destination
WHAT HAPPENED

Towns within 120 miles: Eugene, Cottage Grove. from Eugene: 110 + 90 = 200; from Cottage Grove: 80 + 90 = 170. Keep the smallest: best(Roseburg) = $170, arriving from Cottage Grove.

townbestfrom
Salem$0start
Eugene$110Salem
Cottage Grove$80Salem
Roseburg$170Cottage Grove
Medford··
Ashland··
CS 351

The answer, read backward

Salemmile 0start$0Eugenemile 59hotel $110$110Cottage Grovemile 79hotel $80$80Roseburgmile 129hotel $90$170Medfordmile 223hotel $140$310Ashlandmile 236destination$170
WHAT HAPPENED

best(Ashland) = $170. Follow 'from' backward: Ashland ← Roseburg ← Cottage Grove ← Salem. Two nights, Cottage Grove then Roseburg. Medford's $310 was computed and never used; that is normal.

townbestfrom
Salem$0start
Eugene$110Salem
Cottage Grove$80Salem
Roseburg$170Cottage Grove
Medford$310Roseburg
Ashland$170Roseburg
CS 351

Try it: the road trip

CS 351
// SECTION

Cutting a Douglas fir log

Choices, a recurrence, a table, and reading the answer back

O(n²)O(n)O(log n)

A sawmill's question

THE USE CASE

A mill has an 8-foot Douglas fir log and a price list by length. It can cut the log into any whole-foot pieces. Which cuts bring in the most money?

length (ft)12345678
price ($)158910171720
8 ft
  • Brute force: each of the 7 dashed lines is cut or not: 27 = 128 patterns. A 40-foot log: 5 × 1011.
  • The last choice, again: what is the first piece? After cutting it off, what remains is a shorter log, and it should be sold as well as possible.
  • rev(L) = max over first pieces i = 1..L of price[i] + rev(L − i); rev(0) = 0.
CS 351

The six questions for the log

AskAnswer
Subproblemsrev(L) = most money for a log of L feet; L = 0..n, so n + 1 of them
Relaterev(L) = max1 ≤ i ≤ L ( price[i] + rev(L − i) ): try every first piece
Orderincreasing L
Base caserev(0) = 0
Originalrev(n)
Timen + 1 subproblems × O(n) choices each = O(n²)
CS 351

Fill the table: a 3-foot log

3 ft: $8
EVERY FIRST PIECE

1 ft: 1 + rev(2) = 6; 2 ft: 5 + rev(1) = 6; 3 ft: 8 + rev(0) = 8. Best: rev(3) = $8, first piece 3 ft.

L012345678
rev0158·····
cut—123·····

rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.

CS 351

Fill the table: a 5-foot log

2 ft: $5the rest: rev(3) = $8
EVERY FIRST PIECE

1 ft: 1 + rev(4) = 11; 2 ft: 5 + rev(3) = 13; 3 ft: 8 + rev(2) = 13; 4 ft: 9 + rev(1) = 10; 5 ft: 10 + rev(0) = 10. Best: rev(5) = $13, first piece 2 ft.

L012345678
rev01581013···
cut—12322···

rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.

CS 351

Fill the table: an 8-foot log

2 ft: $5the rest: rev(6) = $17
EVERY FIRST PIECE

1 ft: 1 + rev(7) = 19; 2 ft: 5 + rev(6) = 22; 3 ft: 8 + rev(5) = 21; 4 ft: 9 + rev(4) = 19; 5 ft: 10 + rev(3) = 18; 6 ft: 17 + rev(2) = 22; 7 ft: 17 + rev(1) = 18; 8 ft: 20 + rev(0) = 20. Best: rev(8) = $22, first piece 2 ft.

L012345678
rev01581013171822
cut—12322612

rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.

CS 351

The answer, read backward

2 ft, $56 ft, $17
  • rev(8) = $22.
  • cut[8] = 2: sell a 2-foot piece, then a log of 6 feet remains.
  • cut[6] = 6: sell it whole. Pieces: 2 + 6 ft, $5 + 17 = $22.
  • Check against the obvious patterns: whole log $20; four 2-foot pieces $20; 6 + 1 + 1 $19.
L012345678
rev01581013171822
cut—12322612

rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.

CS 351

Log cutting in Python, bottom-up

def best_revenue(price: list[int], length: int) -> tuple[int, list[int]]:
    rev = [0] * (length + 1)              # rev[L]: best money for L feet
    first_cut = [0] * (length + 1)        # the first piece that achieved it
    for L in range(1, length + 1):        # smaller logs first
        for piece in range(1, L + 1):     # every possible first piece
            candidate = price[piece] + rev[L - piece]
            if candidate > rev[L]:
                rev[L] = candidate
                first_cut[L] = piece
    pieces: list[int] = []                # read the answer backward
    remaining = length
    while remaining > 0:
        pieces.append(first_cut[remaining])
        remaining -= first_cut[remaining]
    return rev[length], pieces
  • Lines 4 and 5: the two loops are the Order and the Relate rows of the table.
  • Line 6: the recurrence, one candidate at a time; line 7 keeps the max.
  • Line 9: remember which choice won, so the answer can be rebuilt.
  • Lines 10 to 14: follow the pointers, exactly like path() in HW4 and HW5.
  • O(n²) time, O(n) space.
CS 351

Try it: the log, every first cut

CS 351
// ACTIVITY

Activity: The log yard

Your turn, in pairs

O(n²)O(n)O(log n)

The log yard

IN PAIRS, ONE WORKSHEET, BOTH NAMES

A different mill, a different price list, a 6-foot log. (a) Fill the rev and cut rows for L = 0..6, showing every candidate for L = 4. (b) Read the best cut pattern back from the cut row. (c) The Sparks Center stairs allow 1, 2, or 3 steps at a time: write the six questions and compute ways(6).

length (ft)123456
price ($)25781013
6 ft

A 6-FOOT LOG, FIVE PLACES TO CUT OR NOT: 32 PATTERNS BY BRUTE FORCE.

CS 351
// CLOSING

Wrap-up

What to keep, and what comes next

O(n²)O(n)O(log n)

The one-slide version

  • Use it when: a best value or a count over a sequence of choices, where the same smaller questions keep coming back.
  • The habit: ask what the last (or first) choice was; the rest is a smaller instance of the same problem.
  • The six questions: Subproblems, Relate, Order, Base cases, Original, Time. Write them down every time.
  • Two implementations: memoized recursion (a cache) or a bottom-up loop in topological order. Same table.
  • Reconstruct with a pointer table, the way parent[] rebuilt a shortest path.
  • Next: choosing subproblems when the input is a string or two: prefixes, suffixes, substrings.
CS 351

References

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, Introduction to Algorithms, 4th ed. MIT Press, 2022. Sections 14.1 and 14.2 (rod cutting and the elements of dynamic programming).
  2. R. Bellman, “The theory of dynamic programming,” Bulletin of the American Mathematical Society, vol. 60, no. 6, pp. 503–515, 1954.
  3. D. E. Knuth and M. F. Plass, “Breaking paragraphs into lines,” Software: Practice and Experience, vol. 11, no. 11, pp. 1119–1184, 1981 (the DP inside TeX).
  4. J. Erickson, Algorithms, 2019, Chapter 3 (Dynamic Programming), https://jeffe.cs.illinois.edu/teaching/algorithms/
CS 351