Skip to the page

Dynamic programming · mid

Dynamic programming, the intro

Dynamic programming solves a problem from answers to smaller overlapping sub-problems, either top-down with memoised recursion or bottom-up with a table. It works once you can write the recurrence and the base cases.

The notes

What you must know

  • Signs of DP: 'count the ways', 'minimum or maximum cost', a choice at each step, and the same sub-problem appearing many times.
  • Steps: define the state (dp[i] = answer for the first i items, or for amount i), write the recurrence, set the base cases, choose the order of filling, then reduce memory.
  • Climbing stairs: dp[i] = dp[i - 1] + dp[i - 2]. House robber: dp[i] = max(dp[i - 1], dp[i - 2] + a[i]). Both need only two variables.
  • Coin change (fewest coins): dp[a] = min(dp[a - c] + 1) over the coins; an unreachable amount stays at 'infinity' and the answer becomes -1. Use amount + 1 as infinity: Integer.MAX_VALUE + 1 overflows in Java. 'Number of ways' loops the coins in the outer loop so that the same coins in another order are not counted twice.
  • LIS: an O(n²) DP first, then O(n log n) with a tails array and binary search.
  • Greedy is not DP: taking the biggest coin first fails for coins [1, 3, 4] and amount 6 (4 + 1 + 1 uses 3 coins, 3 + 3 uses 2).
  • Counts grow fast: climbing stairs with n = 46 already needs more than a 32-bit int (use a 64-bit type in Java and C++; the problem may ask for the answer modulo a number).

The red pen

Common traps: mistake → fix

  • Mistake: Greedy works for coin change

    Fix: only for special coin systems.

  • Mistake: Memoisation and tabulation give different answers

    Fix: same recurrence, different order; tabulation avoids deep recursion.

  • Mistake: Return dp[amount] directly

    Fix: the 'infinity' value must become -1.

Easy to hard

Questions interviewers ask, easy to hard

  1. Climbing stairs: how many ways?
  2. House robber; then the circular version.
  3. Minimum coins for an amount; then the number of ways.
  4. Minimum cost for tickets (1-, 7-, 30-day passes).
  5. Longest increasing subsequence in O(n log n).

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview