Skip to content

What Is Dynamic Programming?

Lesson 1 of 20 · 5 min

What Is Dynamic Programming?

Step 1 of 10

Merge sort on [5, 2, 9, 1]: split at the midpoint, twice, until every piece is a single value.

The Idea

Dynamic programming applies when two things are true: the same subproblem keeps reappearing, and the best whole answer is built from best sub-answers. Merge sort splits into fresh halves that never overlap, so caching buys nothing. Fibonacci's branches collide constantly, so caching buys everything. You already did this by hand in Memoization — DP is that habit, made deliberate.

Real-World Example

A bakery costing out its cake menu. Half the recipes share the same buttercream, so the pastry chef prices one batch of it once and pins the figure to the wall. Every cake using it reads that number instead of re-costing butter, sugar, and labour from scratch.

The Code

Your turn

What does this print?

from functools import lru_cache

@lru_cache(maxsize=None)
def f(n):
  return n if n < 2 else f(n - 1) + f(n - 2)

f(10)
print(f.cache_info().misses)

Mini quiz

1 / 3

Which pair of properties makes a problem a DP problem?