The recipe
Dynamic programming solves a problem by solving smaller versions of it and storing the answers. For probability and game questions:
- Define the state: the smallest description of the situation that determines the future (rolls left, current run length, current total).
- Write the recurrence: the value of a state in terms of the states it can move to, from first-step analysis.
- Fix the base cases and the order in which to fill the table so every value you need is ready.
- State the complexity: number of states times work per state.
Most "simulate it" questions in quant coding rounds have an exact DP answer, and interviewers prefer it.
Worked example
a run of five heads
What is the probability that 100 fair coin flips contain a run of at least five heads?
Show solutionHide solution
The state is the length of the current run of heads (0 to 4), plus an absorbed "done" state. Each flip moves run length to (heads) or (tails), and reaching 5 is absorbed.
def p_run(n: int = 100, k: int = 5) -> float:
dist = [1.0] + [0.0] * (k - 1) # P(current run = r, no run of k yet)
done = 0.0
for _ in range(n):
new = [0.0] * k
for r, p in enumerate(dist):
new[0] += p / 2 # tails resets the run
if r + 1 == k:
done += p / 2 # heads completes the run
else:
new[r + 1] += p / 2
dist = new
return done
This returns about , in time. Most people guess far lower: long runs are more common than intuition suggests.
Distributions by convolution
The distribution of a sum of independent pieces builds up one piece at a time: if is the probability that the first dice sum to , then
This takes for dice instead of enumeration. The same pattern counts paths on grids, ways to make change, and ways to climb stairs.
Optimal stopping by backward induction
With rolls left, the value is the expected payoff under optimal play. On the last roll you must accept: . With more rolls you keep a roll only if it beats continuing:
For infinite-horizon versions with a cost per roll, the value satisfies and the optimal rule is a threshold; solve for it directly or iterate until the value converges.
Worked example
a ten-sided die with two rolls
You roll a fair 10-sided die (faces 1–10) and may roll once more, taking the second result instead. What is the game worth?
Show solutionHide solution
. Keep the first roll if it is 6 or more:
Knowledge check
In how many ways can you climb 10 stairs taking 1 or 2 steps at a time?
Knowledge check
A fair 6-sided die game allows up to two rolls; you may keep the first or take the second. What threshold should the first roll beat to keep it?
Knowledge check
What is the time complexity of computing the full distribution of the sum of n dice by convolution?
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).