DP on Sequences

Linear DP (house robber, decode ways), longest increasing subsequence, two-sequence DP (LCS, edit distance) and state machines (stock problems).

Advanced 3 min readLesson 24 of 25

Most interview DP happens on sequences: arrays and strings. Four shapes cover nearly all of them. Identify which one you're in and the state definition follows.

ShapeStateExamples
Lineardp[i] = answer for the prefix ending at / up to iClimbing stairs, house robber, decode ways, max subarray
LIS-styledp[i] = best subsequence ending at i, looking back at all j less than iLIS, Russian dolls, largest divisible subset
Two sequencesdp[i][j] = answer for prefixes a[0..i) and b[0..j)LCS, edit distance, distinct subsequences, regex matching
State machinedp[i][state] = best at i while in a given stateStock buy/sell with cooldown, fees, k transactions

1. Linear DP: house robber

You can't rob two adjacent houses. Either skip house i (dp[i−1]) or rob it (dp[i−2] + a[i]). Only the last two values are ever needed.

int rob(int[] a) {
    int prev2 = 0, prev1 = 0;                  // dp[i-2], dp[i-1]
    for (int x : a) {
        int cur = Math.max(prev1, prev2 + x);
        prev2 = prev1;
        prev1 = cur;
    }
    return prev1;
}

Decode ways has the same skeleton: dp[i] = (one-digit valid ? dp[i−1] : 0) + (two-digit valid ? dp[i−2] : 0).

2. Longest increasing subsequence

O(n²) DP: dp[i] = 1 + max(dp[j]) over j less than i with a[j] < a[i]. The O(n log n) version keeps tails[k] = the smallest possible tail of an increasing subsequence of length k + 1, and binary searches where each element fits.

10091225334751016187
One LIS: 2, 3, 7, 18 (length 4)
int lengthOfLIS(int[] a) {
    int[] tails = new int[a.length];
    int len = 0;
    for (int x : a) {
        int lo = 0, hi = len;
        while (lo < hi) {                      // first tail >= x
            int mid = (lo + hi) >>> 1;
            if (tails[mid] < x) lo = mid + 1; else hi = mid;
        }
        tails[lo] = x;
        if (lo == len) len++;
    }
    return len;
}

3. Two sequences: LCS and edit distance

Compare the last characters of both prefixes. If they match, extend the diagonal; otherwise take the best of dropping a character from one side.

LCS[i][j]={LCS[i−1][j−1]+1ai=bjmax⁡(LCS[i−1][j], LCS[i][j−1])otherwise\text{LCS}[i][j] = \begin{cases} \text{LCS}[i-1][j-1] + 1 & a_i = b_j \\ \max(\text{LCS}[i-1][j],\ \text{LCS}[i][j-1]) & \text{otherwise} \end{cases}
·acc·abc0000011101120122
LCS of abc and acc = 2 (ac)
Edit distance
int minDistance(String a, String b) {
    int m = a.length(), n = b.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 0; i <= m; i++) dp[i][0] = i;          // delete everything
    for (int j = 0; j <= n; j++) dp[0][j] = j;          // insert everything
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
                ? dp[i - 1][j - 1]
                : 1 + Math.min(dp[i - 1][j - 1],          // replace
                      Math.min(dp[i - 1][j],              // delete
                               dp[i][j - 1]));            // insert
    return dp[m][n];
}

4. State machine: stock problems

Define states for what you hold and update all of them each day. With cooldown: hold, sold (just sold, must rest), rest.

buy −psell +pcooldownrestholdsold
int maxProfit(int[] prices) {                 // with cooldown
    int hold = Integer.MIN_VALUE / 2, sold = 0, rest = 0;
    for (int p : prices) {
        int prevSold = sold;
        sold = hold + p;
        hold = Math.max(hold, rest - p);
        rest = Math.max(rest, prevSold);
    }
    return Math.max(sold, rest);
}

The same machine with a fee subtracted on sell, or with a transaction counter k as an extra dimension, solves the whole stock family.

Practice problems
  • Climbing Stairseasy
  • House Robbermedium
  • House Robber IIrun twice: skip first / skip lastmedium
  • Decode Waysmedium
  • Maximum Product Subarraytrack min and maxmedium
  • Longest Increasing Subsequencemedium
  • Longest Common Subsequencemedium
  • Edit Distancemedium
  • Best Time to Buy and Sell Stock with Cooldownmedium
  • Longest Palindromic SubsequenceLCS with the reversemedium
  • Russian Doll Envelopessort, then LIShard
  • Distinct Subsequenceshard
  • Regular Expression Matchinghard
  • Best Time to Buy and Sell Stock IVk transactionshard
Key takeaways
  • Four shapes: linear, LIS-style, two-sequence, state machine.
  • Linear DP usually needs only the last one or two values.
  • LIS in O(n log n) with tails and binary search.
  • Two-sequence DP: a padded (m+1) × (n+1) table, compare the last characters.
  • State machines: one variable per state, all updated each step.