Log inStart free
LESSON 3.09 · 6 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

Dynamic programming

Watch a slow recursion repeat itself, then a table solve each amount once.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 3.09 · DP BAY24 CALLS FOR AMOUNT 6
01
Stage 1 of 6 · Plain recursion
The recursion tries each coin, then solves the smaller amount the same way. Amount 6 makes 24 calls.
Explain it simply

Say you need to pay 6 with coins worth 1, 3 and 4, using as few coins as you can. The recursion tries each coin as the last one. Then it solves the amount that's left in the same way. Each bar in the tree is one call, and the bars under it are the calls it makes.

A call tree for amount 6 with coins 1, 3 and 4. It has 24 calls in 7 rows. The first call asks about amounts 5, 3, 2.

amount, first callcoinrepeated work, no way (∞)stored answer, memo hitdead end, empty cell
call treecoins134f(6)f(5)f(4)f(3)f(2)f(1)f(0)f(0)f(1)f(0)f(0)f(2)f(1)f(0)f(1)f(0)f(3)f(2)f(1)f(0)f(0)f(2)f(1)f(0)f(6) = 1 + min(f(5), f(3), f(2)) · 24 callsanswersamount0123456call treecoins134f(6)f(5)f(4)f(3)f(2)f(1)f(0)f(0)f(1)f(0)f(0)f(2)f(1)f(0)f(1)f(0)f(3)f(2)f(1)f(0)f(0)f(2)f(1)f(0)f(6) = 1 + min(f(5), f(3), f(2)) · 24 callsanswersamount0123456
Toy: fewest coins for one amount · 3 coin sets · amounts 4 to 8 · the work chart runs to 12
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
f(n)=1+min⁡c≤nf(n−c),f(0)=0\sy{f}{out}{f}(\sy{n}{data}{n}) = 1 + \min_{\sy{c}{param}{c} \le n} \sy{f}{out}{f}(\sy{n}{data}{n} - \sy{c}{param}{c}),\quad f(0) = 0
f(6)=1+min⁡(f(5), f(3), f(2))f(6) = 1 + \min(f(5),\ f(3),\ f(2))

The fewest coins for n is one coin plus the best smaller amount.

Common mix-ups

MYTHRecursion is slow because function calls are slow.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With coins 2 and 5, what does the table hold for amount 3?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.