Fifty years of work, and a warm-up you just ran by hand, point at one idea. Here it is, precisely.
Dynamic programming is a technique for solving optimization (or
counting) problems by breaking them into subproblems, solving each distinct subproblem exactly once, storing its answer, and
combining stored answers - applicable exactly when a problem has
both optimal substructure and overlapping subproblems.
CLRS (Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms) 4th ed - Ch 14, Sections 14.1 (rod cutting) and 14.3 (elements of dynamic programming).
Optimal substructure alone is what already let D&C (Week 9) and
greedy (Week 10) work directly, with nothing stored.
The extra ingredient DP adds is storage: cache or tabulate each
distinct subproblem's answer, once.
Key Words Today
Recurrence relation: an equation defining a problem's answer in
terms of the answers to its own smaller subproblems.
Base case: the smallest subproblem(s), answered directly, with
no further recursion - where the recurrence bottoms out.
DP table / state: the structure (often an array or grid) that
holds one stored answer per distinct subproblem.
Knapsack problem: choosing a subset of items, each with a cost
and a value, to maximize total value under a shared budget - the
Tour Planner's actual shape.
Condition 1: Optimal Substructure - Shared With Greedy, Except...
The same property that made greedy work last week. Almost.
Definition: the best overall answer is built from the best
answers to its own subproblems.
Tour Planner has it: the best 60-minute plan either includes the
live music or it doesn't - whichever way, the rest of the plan must
be the best possible plan for whatever time and activities remain.
The Catch: What DP Adds That Greedy Doesn't
Same optimal substructure. A different response to it.
Greedy commits to one locally-best choice and never looks back - it
bets that today's best-looking option can't hurt the final answer.
DP's insight is that when the locally-best choice can be wrong -
no greedy-choice property (Week 10) - you must consider a
subproblem's answer under every relevant scenario, not just the
one greedy would have picked.
Concretely: greedy Tour Planner asks "what's best right now?" once,
per step. DP asks "what's the best plan for every remaining
time budget?" and keeps all of those answers around, in case a
later choice needs one it hasn't picked yet.
Test: room-booking (Week 10) has the greedy-choice property, so
greedy alone sufficed. Tour Planner does not (the greedy attempt on
the pain slide already showed it) - it needs the full machinery.
Condition 2: Overlapping Subproblems - Where Have We Seen This?
Week 4's `fib(5)` call tree slide, revisited.
Definition: the same smaller subproblem recurs many times while
solving the bigger one.
Naive recursive fib(n) = fib(n-1) + fib(n-2): the call tree
re-derives fib(3) twice, fib(2) three times, and so on -
exponentially many repeats as grows. That is overlapping
subproblems, exactly.
Contrast with divide-and-conquer (Week 9): merge sort's
subproblems are each half of the array - they never repeat. That
is exactly why D&C never needed to cache anything.
A problem needs both conditions before caching is worth doing.
Optimal substructure with no overlap is just recursion (or greedy);
overlap with no optimal substructure isn't an optimization problem
at all.
CLRS's Classic Version: Rod Cutting
Same idea, a different costume - the textbook's own worked example.
CLRS Section 14.1 develops this exact recurrence on a different
problem, rod cutting: given a rod of length and a price for
each possible cut length, choose a set of cuts that maximizes total
revenue.
Rod cutting (CLRS 14.1)
Tour Planner (this deck)
A rod of length
A 60-minute free block
Each possible cut length, with its own price
Each activity, with its own duration and enjoyment
Choose cuts to maximize total revenue under length
Choose activities to maximize enjoyment under 60 minutes
Rod Cutting: The Same Optimal Substructure
Not just a similar-looking table - the identical argument.
CLRS's rod-cutting recurrence says: the best revenue for a rod of
length either leaves the rod uncut, or makes one cut and adds the
best revenue for whatever length remains. That is the same choice
structure as best(i,t) (introduced shortly) - "include this option
or don't, then solve optimally for what's left" - applied to a length
budget instead of a time budget.
This is why the paradigm, not the problem, is what transfers: once you
can write "include this option or don't, then recurse on the
remainder," you can solve rod cutting, the Tour Planner, or any other
0/1-choice-under-a-budget problem with the same recurrence shape.
Quantifying the Blow-Up
Not a vague "it's slow." Actual numbers.
Naive recursive calls
Loop iterations (memo/tabulation)
10
177
10
20
21,891
20
30
2,692,537
30
What 90,000x More Work Actually Means
Same table. Now: why the gap gets worse, not better, as n grows.
At , the naive approach performs roughly 90,000× more work
than necessary - to compute the exact same number. This is the same
shape of gap you've seen between a slow growth rate and a fast one all
semester, just far more dramatic: here the bad approach isn't linear,
it's exponential ( calls) against a fix that's linear ().
The naive tree's redundant work doubles, roughly, with every
added step - the fix's loop only adds one more addition.
This is exactly why "it worked on my small test case" is not
evidence a recursive solution scales: the naive version is fine at and catastrophic by .
Two Implementations, One Recurrence
The single most common DP misconception: these are NOT two different algorithms.
Memoization (top-down)
FIB_MEMO(n, cache):
if n <= 1:
return n
if cache[n] is set:
return cache[n]
cache[n] = FIB_MEMO(n-1, cache)
+ FIB_MEMO(n-2, cache)
return cache[n]
Tabulation (bottom-up)
FIB_TAB(n):
table[0] = 0
table[1] = 1
for i = 2 to n:
table[i] = table[i-1]
+ table[i-2]
return table[n]
Two Implementations, Continued: Only Direction Differs
Same recurrence as the code on the previous slide.
Same recurrence, same distinct subproblems solved exactly once,
same time. Only the direction differs: memoization recurses
top-down and fills the cache lazily; tabulation iterates bottom-up and
fills every entry, in order, up front.
Fibonacci-shaped DP · worked example 1 of 3 (simple)
Fill the Table by Hand: table[0..6]
Two seed values, then the recurrence, one cell at a time.
GoalUsing table[i] = table[i-1] + table[i-2], fill table[0] through table[6].
1
Seeds
table[0] = 0, table[1] = 1 - the two base cases, given directly, no recursion needed.
→
2
table[2..4]
table[2]=0+1=1. table[3]=1+1=2. table[4]=1+2=3.
→
3
table[5..6]
table[5]=2+3=5. table[6]=3+5=8.
✓
Conclusiontable[6] = 8 - each cell only ever reads the two cells directly before it.
💡
Key takeawayNothing here is ever recomputed or re-derived from scratch - that's the entire payoff, visible even on 7 cells.
Fibonacci-shaped DP · worked example 2 of 3 (moderate)
Tabulation, Memoization, and the Cache Fill
Same recurrence, two directions - watch memoization's repeats turn into cache hits.
GoalCompare tabulation's table trace to memoization's call tree, on fib(5) through fib(7).
1
Tabulation trace
i
0
1
2
3
4
5
6
7
table[i]
0
1
1
2
3
5
8
13
table[7] reads two solved neighbors, writes 5+8=13.
2
Memo call tree
FIB_MEMO(5) makes 9 calls total, not 15: FIB_MEMO(4) and FIB_MEMO(3)'s second visits are cache HITs, not new subtrees.
3
Cache-fill order
cache[2]=1+0=1, cache[3]=1+1=2, cache[4]=2+1=3, cache[5]=3+2=5 - filled in the same ascending order as tabulation.
4
Only direction differs
Tabulation reaches 2,3,4,5 by looping forward. Memoization reaches the same order by recursing all the way down to the base cases first, then filling on the way back up.
✓
ConclusionBoth implementations solve the identical recurrence, same cells, same values - only the fill order's direction differs.
💡
Key takeaway"Which one is faster" is the wrong question - they do the same O(n) work. "Which order do I need results in" is the right one.
Fibonacci-shaped DP · worked example 3 of 3 (harder)
The Real Feature: The 20-Step Shortcut Counter
Week 9 sped this up numerically. Week 4's handout showed its naive recursion explode. Now, properly.
GoalCount distinct ways to climb 20 steps, 1 or 2 at a time - correctly and fast.
1
Recurrence
ways(n) = ways(n-1) + ways(n-2), ways(0)=1, ways(1)=1 - Fibonacci's recurrence, wearing a different costume. Optimal substructure: a way to climb n steps is [any way to climb n-1] + a final 1-step, or [any way to climb n-2] + a final 2-step.
→
2
Overlap
ways(18) is needed by both ways(19) and ways(20), and by every larger step count above it - overlapping subproblems, exactly.
→
3
Tabulate
n=0..8: 1,1,2,3,5,8,13,21,34. Continuing the same loop to n=20 gives ways(20) = 10,946 - 20 additions, not the millions the naive tree implied at that depth.
★
Could greedy solve this?
No greedy-choice property exists here: a 1-step hop isn't "better" than a 2-step hop in isolation, since the final count needs BOTH branches counted, not one picked and the other discarded - exactly DP's combination, not greedy's.
✓
Conclusionways(20) = 10,946 distinct routes, computed with just 20 additions, not millions.
💡
Key takeawayNo locally-best hop exists - both branches must be counted, not discarded, which is why this needs DP.
Tour Planner: Conditions and Recurrence
Back to the greedy Tour Planner's failure. Let's test the two conditions and fix it for real.
Free block: 60 minutes. Activities: Coffee (20 min, enjoyment 15),
Gallery (30 min, enjoyment 25), Friend (10 min, enjoyment 8), Music
(40 min, enjoyment 40). Do each at most once; maximize total enjoyment
without exceeding 60 minutes.
Optimal substructure? Yes - the best plan either includes Music
or it doesn't; either way, the rest must be the best possible plan
for whatever time and activities remain.
Overlapping subproblems? Yes - "best plan for 20 minutes using
{Coffee, Gallery, Friend}" gets asked whether or not Music is
chosen, and other branches ask it too.
The Tour Planner's Recurrence
Both conditions hold - here's the recurrence that follows from them.
Recurrence (best(i,t) = best value using the first
activities within minutes):
(the second term only applies if - you can't
spend time you don't have.)
Tour Planner (0/1 knapsack) · worked example 1 of 3 (simple)
Two Options, 10 Minutes: Snack or Nap
The smallest case that still shows a real include-or-not decision.
GoalBudget 10 minutes. Snack (5 min, value 6) or Nap (8 min, value 10).
1
Setup
Two options, one 10-minute budget - only one substantial item fits, plus scraps of time.
ConclusionEvery row-column combination in the table follows the same two-case recurrence, whether the choice is close (row +Friend) or lopsided (the final cell).
💡
Key takeawayReading a filled table backward, cell by cell, is exactly how you'd check a claimed answer's work.
Tour Planner (0/1 knapsack) · worked example 3 of 3 (harder)
Inside the Cell Where Greedy Went Wrong
Ratio-based greedy committed to Music immediately. Here's the table cell that proves it right anyway - for the wrong reason.
GoalShow exactly which comparison DP makes that greedy's ratio rule never does.
1
Where greedy went wrong
Ratios: Coffee 15/20=0.75, Gallery 25/30≈0.83, Friend 8/10=0.80, Music 40/40=1.00. Best ratio (Music) taken first, 40 of 60 min used; then Friend fits (10 more); Coffee (20 min) no longer fits in the remaining 10. Result: 48 enjoyment, 10 min unused.
Including Music wins this sub-decision too - matching DP's eventual full-budget answer of 55 (Coffee+Music), not greedy's 48.
★
Why greedy misses this
Ratio-based greedy commits to Music immediately, without ever checking whether pairing something else with Coffee's leftover budget could beat it. DP keeps every remaining-budget scenario alive - all 7 columns, every row - until the comparison in step 3 actually gets made.
✓
Conclusionbest(4,40) = 40 - DP proves including Music is right here, but only by comparing against every alternative, not by trusting a ratio.
Inside the Cell, Continued: The Real Payoff
One cell's comparison, and what it says about the whole technique.
💡
Key takeawayGreedy asks "what looks best right now?" once. DP asks it for every possible remaining budget, then lets the table itself decide.
CampusNav: Tour Planner + Shortcut Counter, Both Solved
Two features, one technique, both provably correct now.
The Tour Planner now recommends the actual best combination of
nearby activities for any free block - not a locally-greedy guess -
using the 0/1 knapsack recurrence above, in time via tabulation.
The 20-step shortcut counter, first attempted recursively back
in Week 4's handout/worksheet (where its call tree was shown to blow
up) and sped up numerically in Week 9, is now solved the "right"
way: a genuine DP that both counts routes and explains why it's fast
(overlapping subproblems, cached).
Both features ship as the same shape of code: a small table, filled
once, in one pass.
CampusNav's Real Scale, Compared
The 4-activity, 20-step examples above were hand-traceable. The real feature is bigger.
At CampusNav's real scale (30 nearby activities, a 120-minute budget),
the Tour Planner's table needs roughly cells -
versus (over a billion) possible activity subsets to
brute-force. Polynomial cells instead of exponential combinations is
DP's entire payoff, at a scale no hand trace could ever reach.
Common Mistakes
"Memoization and tabulation are different algorithms." No -
they implement the exact same recurrence. Only the direction of
computation differs (top-down + cache vs. bottom-up + table); the
code shapes look different, which is exactly why this is tempting.
"If a problem is solved recursively, it automatically needs DP."
Not true - merge sort (Week 9) is recursive, but its subproblems
(each half of the array) never repeat. No overlap means caching buys
nothing but bookkeeping overhead.
"Optimal substructure alone is enough to justify DP." Optimal
substructure alone is what greedy and D&C already exploit, with
nothing stored. DP earns its keep only when overlap is also
present.
Key Words Today
State: the specific subproblem a DP table cell represents - e.g.
"best value using the first activities within minutes."
State space: the full set of distinct states a DP table must
cover - its size determines the table's dimensions and runtime.
0/1 knapsack: the specific knapsack variant where each item is
either fully taken or fully left out (no splitting) - exactly the
Tour Planner's shape.
Bottom-up order: the requirement that, by the time tabulation
computes a cell, every cell it depends on must already be filled.
Why This Shows Up in Interviews, Too
This isn't only about CampusNav.
Search "dynamic programming," "knapsack," or "memoization" in any
technical interview question bank and you'll find hundreds of
problems - Fibonacci variants, coin change, longest paths, edit
distance. Interviewers test exactly this recognition skill: can you
tell, on sight, whether a new problem has both required conditions,
and can you write down its recurrence before writing a single line of
code?
Real systems lean on the same trick constantly: compilers reuse
optimized sub-expressions, spell-checkers reuse edit-distance
subcomputations, and route planners reuse the best-known cost to
intermediate stops - all dynamic programming, under different names.
What Today's Dynamic Programming Cannot Do
DP now conquers 1-D optimization: a single sequence of choices,
indexed by one running quantity (time, position, or step count). But
many real problems compare or align two separate sequences at
once - two students' course schedules, two DNA-like strings, two
playlists - and a 1-D recurrence like today's has no second dimension
to index the second sequence against.
Next Week
Week 11 leaves comparing or aligning two separate sequences at
once unsolved. Week 12, Dynamic Programming II, addresses it:
CampusNav's "find a study buddy" feature - comparing two students'
weekly course-code sequences - via the Longest Common Subsequence, a
genuinely 2-D DP recurrence.
Where This Week Lives in CLRS
Everything above, mapped to the textbook.
Topic this week
CLRS 4th ed
Rod cutting (structural twin of the Tour Planner)
§14.1
Optimal substructure + overlapping subproblems, memoization vs. tabulation
§14.3
If you want to go deeper (not required this week):
CLRS §14.2, matrix-chain multiplication - a harder 2-D DP problem
where the choice is *where* to place parentheses, not *whether* to
include an item. Week 12 starts down that same 2-D road with a
different problem (longest common subsequence).
Summary
Two necessary conditions - optimal substructure and overlapping
subproblems - decide whether a problem is worth tabulating at all.
Memoization and tabulation are two implementations of the same
recurrence, not two different algorithms.
The Tour Planner (0/1 knapsack) and the 20-step shortcut counter
(climbing stairs) are both solved, provably optimally, with the
exact same DP machinery Fibonacci taught us.
New: Week 11 Check - a short graded exercise on today's two DP
techniques, released now, due before Week 12 begins (see materials/assignments/week11-check.html).
Summary, Continued
Reminder: Assignment 2 (Sorting) results are being returned and
discussed this week.
Reading: CLRS, Chapter 14 (Dynamic Programming), Sections 14.1
(rod cutting) and 14.3 (elements of dynamic programming).
Prepare: think of two sequences you'd want to compare (two class
schedules, two playlists, two strings) - bring one to Week 12.
Thank You
SLOT 1: Title
notes: Welcome the class. Remind them: "Last week you proved greedy could be wrong - the campus-points {1,3,4} example where the greedy answer wasn't the best one." That is today's hook.
SLOT 2: Where we are
notes: Point at the row. Say: "Eleven weeks of CampusNav so far. Today its Tour Planner feature finally gets solved properly."
SLOT 3: Recap + open wound
SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon
notes: Do not say "greedy," "optimal," or "algorithm" as the point of failure yet - let the class feel that the one-rule pick left something on the table.
notes: Pause after showing the second bar. Say: "This is not a bug in the code - it is a bug in the plan."
SLOT 5: Cost of not knowing
SLOT 6: Driving question
SLOT 7: Learning outcomes
Key Words Today, session 1 (kept after Act 1 / MOTIVATE per SPINE.md's no-definition-before-slot-8 rule)
notes: Read each term aloud once. Say these four words are today's whole vocabulary, formalized one at a time.
SLOT 8: Origin
SLOT 9: Core concept
Key Words Today, session 2
notes: Read each term aloud. These pair directly with today's two worked examples.
Act 3 / BUILD: Condition 1
Act 3 / BUILD: Condition 2
Rod-cutting comparison, CLRS's classic version of this same idea
Act 3 / BUILD: quantify the blow-up
Idea + pseudocode: the two DP implementations, technique 1 (Fibonacci-shaped)
Dense worked example, Fibonacci-shaped DP, simple tier (absorbs cut Check-Yourself)
Dense worked example, Fibonacci-shaped DP, moderate tier
Dense worked example, Fibonacci-shaped DP, harder tier (real feature + greedy-check, absorbs cut Check-Yourself)
Second technique: 0/1 knapsack (Tour Planner). Idea + recurrence merged.
Dense worked example, knapsack-shaped DP, simple tier
Dense worked example, knapsack-shaped DP, moderate tier (full DP table, too large for a card - shown full-width)
Dense worked example, knapsack-shaped DP, moderate tier, continued: how the table was actually filled
Dense worked example, knapsack-shaped DP, harder tier (inside one cell + greedy contrast)
SLOT N-2: Worked example
SLOT N-1: Common mistakes
Key Words Today, session 3
notes: Read each term aloud. Say: "state" and "state space" return constantly for the rest of the semester, including graphs in Weeks 13-14.