AlgoFrames

The DP recipe: state, transition, base cases, order, answer

Every DP answers five questions: the state, the transition, the base cases, the fill order and where the answer lives.

Before you start: Tabulation: filling the table bottom-up.

The idea

Before any dynamic programming code, answer five questions. Each slot below is empty until you can say it in one line.

The slots work for every DP in this course. Once they are filled, the code is a loop that follows them.

Intuition

Min cost climbing stairs, solved on paper: every slot has a one-line answer, and the table on the right holds the result.

Leaving step i costs cost[i]. A move climbs 1 or 2 steps, and you may start on step 0 or 1. The top is one past the last step.

The state names what each cell means. Cell 4 holds 20: the cheapest way to stand on the top, which is the answer.

A state must hold everything the future needs. Here, where you stand is enough. The cost list never changes, so it is not part of the state.

Complexity

Plain recursion recomputes the same cells over and over. The table does n + 1 cells with 2 reads each: O(n) time.

Time is the number of states times the work per state. Plain recursion on the same recurrence grows like 1.6ⁿ; see Memoization.

The table holds n + 1 cells, so space is O(n). Each cell reads only the last two, so two variables would give O(1).

Look at the transition to see which cells it reads. If it reaches back a fixed distance, a short window replaces the table.

Pitfalls

Setting dp[0] = cost[0] charges for a step you never leave. Starting on step 0 or 1 is free, so both base cases are 0.

A wrong base case poisons every cell after it. Read the problem statement again for what the first states cost.

The top is one past the last step, so it is dp[n], not dp[n − 1]. The table needs n + 1 cells.

The answer slot is a separate decision from the state. Say where the answer lives before you allocate the table.

Variations

A new problem, the same five slots. House robber changes the state's meaning and the transition, not the recipe.

With two coordinates the state becomes dp[r][c], and the order becomes two nested loops. Cell (2, 2) reads the cells above and left.

Code

Pseudocode

minCostClimb(cost):
  n ← length of cost
  dp ← array of size n + 1
  dp[0] ← 0; dp[1] ← 0
  for i from 2 to n:
    dp[i] ← min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
  return dp[n]

Python

def min_cost_climb(cost):
    n = len(cost)
    dp = [0] * (n + 1)
    dp[0] = 0
    dp[1] = 0
    for i in range(2, n + 1):
        dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
    return dp[n]

JavaScript

function minCostClimb(cost) {
  const n = cost.length;
  const dp = new Array(n + 1).fill(0);
  dp[0] = 0;
  dp[1] = 0;
  for (let i = 2; i <= n; i++) {
    dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
  }
  return dp[n];
}

Java

static int minCostClimb(int[] cost) {
    int n = cost.length;
    int[] dp = new int[n + 1];
    dp[0] = 0;
    dp[1] = 0;
    for (int i = 2; i <= n; i++) {
        dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
    }
    return dp[n];
}

Practice problems (7)

Identify the state Warm-up

Min cost climbing stairs: leaving step i costs cost[i], a move climbs 1 or 2 steps, and you may start on step 0 or step 1. You want the cheapest way to reach the top.

Which meaning of dp[i] is a good state?

Match each slot to its meaning Warm-up

Match each slot of the DP recipe to the question it answers.

Write the transition Standard

Complete the min cost climbing stairs function. dp[i] is the cheapest cost to stand on step i, and the top is step n.

Fill the three blanks.

Min cost climbing stairs Standard

You climb a staircase. Leaving step i costs cost[i], and a move climbs 1 or 2 steps. You may start on step 0 or step 1, and the top is the position one past the last step.

Return the minimum total cost to reach the top.

Write down the five slots first: state, transition, base cases, order and answer.

Fill the min-cost table Standard

Costs are [5, 2, 8, 1, 9, 3]. Use dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]) with dp[0] = dp[1] = 0. Work out each cell before the trace writes it.

Stair points Standard

Step i of a staircase gives points[i] points. You start on step 0, each move climbs 1 or 2 steps, and you must finish on the last step. You collect the points of every step you stand on. Points can be negative.

Return the most points you can collect.

Fill the five slots before you code.

Apply the recipe to a new problem: house robber Challenge

A street has houses in a row. House i holds loot[i]. Robbing two neighbouring houses sets off an alarm, so you may not rob two houses that are next to each other.

Return the most loot you can take.

This problem is new: write down the state, transition, base cases, order and answer yourself, then code them.

Related topics

Next on the path: 1-D DP: house robber, decode ways, jump game II