Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Dynamic programming

Write the recursion, notice the repeats, fill a table in an order that makes each entry final.


When it applies

0 1 2 1 1 2 2 0123456 best[6] = best[3] + 1 every smaller amount is already final fill in an order that makes each entry final

Dynamic programming is for problems with overlapping subproblems and an optimal substructure: the best answer for a state is built from the best answers of smaller states. Always write the recursion first and only then decide between memoising it and filling a table bottom-up.

Signals: "fewest", "number of ways", "maximum value subject to", and any brute force whose recursion tree visibly repeats arguments.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

best = [BASE] + [SENTINEL] * n
for state in range(1, n + 1):
    for move in moves(state):
        prev = state - move
        if prev >= 0:
            best[state] = min(best[state], best[prev] + cost(move))
return best[n]

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.