Skip to lesson

A rigorous 4-step framework eliminates guesswork and turns complex optimization problems into mechanical dynamic programming solutions.

Step 1 and 2: Define the state and list choices

In dynamic programming, the state is what a subproblem is described by, such as dp[i], and the transition is the formula that builds a state's answer from smaller states.

The most frequent mistake in dynamic programming is writing code before defining state semantics. Always state the meaning of a table cell in plain English first. For example, declare that dp[i] represents the maximum profit using prefixes up to index i.

Once the state meaning is unambiguous, enumerate all possible decisions at that step. In house robbery, you have exactly two choices at house i. You can rob house i and add its loot to dp[i-2]. Alternatively, you can skip house i and carry forward dp[i-1].

Every decision corresponds to a distinct transition branch. Expressing choices explicitly prevents missing edge cases or omitting viable subproblem pathways. Clear state definitions also reveal whether extra dimensions are required.

Step by step

Step 1 of 4

Array: 0, 2, 0, 0, 0.
idx
1
loot
2
Define dp[i] as maximum loot from first i houses. Base cases: dp[0]=0, dp[1]=2.

Step 3 and 4: Recurrence relation, base cases, and location

Step three translates English choices directly into a mathematical recurrence relation. For maximization problems, wrap competing choices inside a Math.max function call. For minimization problems, wrap alternative pathways inside a Math.min call.

Example 1 · House Robber DP Recipe

RecipeHouseRobber.javaJava
public class RecipeHouseRobber {    public static int rob(int[] nums) {        if (nums == null || nums.length == 0) return 0;        int n = nums.length;        if (n == 1) return nums[0];
        // Step 1: dp[i] is max loot from first i houses        int[] dp = new int[n + 1];
        // Step 4: Base cases        dp[0] = 0;        dp[1] = nums[0];
        // Step 2 & 3: Choices and recurrence        for (int i = 2; i <= n; i++) {            int robCurrent = nums[i - 1] + dp[i - 2];            int skipCurrent = dp[i - 1];            dp[i] = Math.max(robCurrent, skipCurrent);        }
        return dp[n];    }
    public static void main(String[] args) {        int[] houses1 = {2, 7, 9, 3, 1};        System.out.println("Max loot 1: " + rob(houses1));        int[] houses2 = {1, 2, 3, 1};        System.out.println("Max loot 2: " + rob(houses2));    }}
Output
Max loot 1: 12
Max loot 2: 4

What this code does

  • State dp[i] represents maximum profit achievable using the first i houses.
  • At each house i, the algorithm balances robbing house i against skipping it.
  • Outputs 12 and 4 match optimal selections {2, 9, 1} and {1, 3}.

Example 2 · Minimum Cost Train Tickets

RecipeMinCostTickets.javaJava
import java.util.HashSet;import java.util.Set;
public class RecipeMinCostTickets {    public static int mincostTickets(int[] days, int[] costs) {        Set<Integer> travelDays = new HashSet<>();        for (int d : days) travelDays.add(d);        int lastDay = days[days.length - 1];
        // Step 1: dp[d] = min cost to travel up to day d        int[] dp = new int[lastDay + 1];
        for (int d = 1; d <= lastDay; d++) {            if (!travelDays.contains(d)) {                dp[d] = dp[d - 1];            } else {                int cost1 = dp[d - 1] + costs[0];                int cost7 = dp[Math.max(0, d - 7)] + costs[1];                int cost30 = dp[Math.max(0, d - 30)] + costs[2];                dp[d] = Math.min(cost1, Math.min(cost7, cost30));            }        }        return dp[lastDay];    }
    public static void main(String[] args) {        int[] days = {1, 4, 6, 7, 8, 20};        int[] costs = {2, 7, 15};        System.out.println("Min ticket cost: " + mincostTickets(days, costs));    }}
Output
Min ticket cost: 11

What this code does

  • State dp[d] defines the minimum cost to cover travel needs up to calendar day d.
  • Non-travel days inherit cost from the preceding day without extra expenditure.
  • Travel days evaluate 1-day, 7-day, and 30-day ticket purchasing choices.

Example 3 · Counting Unique BSTs

RecipeUniqueBST.javaJava
public class RecipeUniqueBST {    public static int numTrees(int n) {        // Step 1: dp[i] = number of unique BSTs with i distinct keys        int[] dp = new int[n + 1];
        // Step 4: Base cases        dp[0] = 1;        dp[1] = 1;
        // Step 2 & 3: Choices - each j from 1 to i can act as root        for (int i = 2; i <= n; i++) {            for (int j = 1; j <= i; j++) {                int leftTrees = dp[j - 1];                int rightTrees = dp[i - j];                dp[i] += leftTrees * rightTrees;            }        }        return dp[n];    }
    public static void main(String[] args) {        System.out.println("BSTs for n=3: " + numTrees(3));        System.out.println("BSTs for n=4: " + numTrees(4));        System.out.println("BSTs for n=5: " + numTrees(5));    }}
Output
BSTs for n=3: 5
BSTs for n=4: 14
BSTs for n=5: 42

What this code does

  • State dp[i] counts the total number of unique BST structures formed with i nodes.
  • Choosing root j leaves j - 1 left nodes and i - j right nodes.
  • Values 5, 14, and 42 correspond to Catalan numbers for sizes 3, 4, and 5.

Step four establishes smallest foundational base cases where transitions cannot fire. Base cases must reflect literal problem constraints without artificial modifications. For instance, zero houses yield zero loot, while one house yields that house's value. Finally, pinpoint where the ultimate answer resides upon loop termination. Usually the answer occupies the final table cell dp[n]. However, problems seeking global peaks across prefixes may require scanning all cells.

Avoiding common state definition pitfalls

Off-by-one errors frequently arise when aligning 1-indexed tables with 0-indexed input arrays. When dp[i] represents prefixes of length i, input element i corresponds to array index i - 1. Be deliberate and consistent with index offsets throughout your code.

Another subtle trap is an incomplete state that omits critical operational constraints. If a problem imposes cooldown periods, a single integer index cannot capture the system. You must augment the state with a boolean flag or secondary state machine dimension.

Lastly, verify that the state dependency graph is strictly a directed acyclic graph. If state A depends on state B while state B depends on state A, cycles break dynamic programming. Cycles necessitate graph shortest path algorithms like Dijkstra instead of linear DP tables.

Next step

Check your understanding

10 quick questions