Skip to content
BytePatterns

What Is Dynamic Programming?

Dynamic Programming: lesson 1 of 20

Solve each overlapping subproblem once, then reuse the answer.

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

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):                       # the same n is asked for again and again
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(50))                    # 12586269025 — instant, because nothing repeats
print(fib.cache_info().hits)      # reads that skipped a whole subtree

Python

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?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.