16. Dynamic Programming, Part 2: LCS, LIS, Coins
16. Dynamic Programming, Part 2: LCS, LIS, Coins
Overview
This lecture continues Dynamic Programming with three classic examples:
- Longest Common Subsequence (LCS) - comparing two sequences
- Longest Increasing Subsequence (LIS) - finding ordered subsequences
- Alternating Coin Game - optimal strategy in two-player games
Key new concepts introduced:
- Multiple sequences: Take product of subproblem spaces
- Substrings: When prefixes/suffixes aren't enough
- Parent pointers: Recovering actual solutions (not just optimal values)
- Subproblem constraints/expansion: Adding parameters to make recurrences work
SRTBOT Review
| Step | Key Lesson |
|---|---|
| S - Subproblems | For sequences: try prefixes, suffixes, or substrings. Want polynomial count. |
| R - Relations | Identify a question about the solution. Brute force all polynomial answers. |
| T - Topological Order | Dependencies must be acyclic. Usually a few for loops. |
| B - Base Cases | Smallest subproblems with known answers. |
| O - Original Problem | Sometimes one subproblem, sometimes combine multiple. |
| T - Time | (# subproblems) × (non-recursive work per subproblem) |
Subproblems for Multiple Inputs
When you have multiple input sequences, multiply the subproblem spaces:
Single sequence A: Subproblems = prefixes/suffixes/substrings of A
Two sequences A, B: Subproblems = (subproblems of A) × (subproblems of B)| # Sequences | Subproblem Count | Feasibility |
|---|---|---|
| 1 | O(n) or O(n²) | ✓ Always fine |
| 2 | O(n²) or O(n⁴) | ✓ Usually fine |
| 3 | O(n³) or O(n⁶) | ✓ Often acceptable |
| k (constant) | O(n^k) or O(n^2k) | ✓ Polynomial |
| n sequences | O(n^n) | ✗ Exponential - infeasible |
Example 1: Longest Common Subsequence (LCS)
Problem Definition
Given two sequences A and B, find the longest sequence L that is a subsequence of both A and B.
Key distinction:
- Substring: Contiguous elements (no gaps)
- Subsequence: Can skip elements (gaps allowed)
Example:
A = "hieroglyphology"
B = "Michelangelo"
LCS = "hello"SRTBOT Solution
Subproblems: L(i, j) = LCS of suffix A[i:] and suffix B[j:]
for i ∈ {0, ..., |A|}, j ∈ {0, ..., |B|}
(|A| + 1) × (|B| + 1) subproblems
Relation: L(i, j) =
If A[i] == B[j]:
1 + L(i+1, j+1) # Match! Include this letter
Else:
max(L(i+1, j), L(i, j+1)) # Skip A[i] or skip B[j]
Topological: for i = |A| down to 0:
for j = |B| down to 0:
compute L(i, j)
Base Cases: L(|A|, j) = 0 for all j # A exhausted
L(i, |B|) = 0 for all i # B exhausted
Original: L(0, 0)
Time: O(|A| × |B|) subproblems × O(1) work = O(|A| × |B|)Understanding the Relation
Case 1: A[i] ≠ B[j] (Different letters)
- At least one of A[i] or B[j] is NOT in the LCS
- Don't know which one, so try both options
- Take max of skipping A[i] vs skipping B[j]
Case 2: A[i] == B[j] (Same letter)
- Claim: Can always include this match in an optimal LCS
- Proof: If some optimal LCS doesn't use A[i] or B[j], we can modify it to use this match without making it shorter
- No need to max with other options—just take the match
def lcs(A, B):
m, n = len(A), len(B)
# L[i][j] = LCS length of A[i:] and B[j:]
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if A[i] == B[j]:
L[i][j] = 1 + L[i + 1][j + 1]
else:
L[i][j] = max(L[i + 1][j], L[i][j + 1])
return L[0][0]Visual Example: "their" vs "habit"
h a b i t (empty)
┌───┬───┬───┬───┬───┬───┐
t │ 2 │ 1 │ 1 │ 1 │ 1 │ 0 │
├───┼───┼───┼───┼───┼───┤
h │ 2 │ 1 │ 1 │ 1 │ 1 │ 0 │
├───┼───┼───┼───┼───┼───┤
e │ 1 │ 1 │ 1 │ 1 │ 1 │ 0 │
├───┼───┼───┼───┼───┼───┤
i │ 1 │ 1 │ 1 │ 1 │ 1 │ 0 │
├───┼───┼───┼───┼───┼───┤
r │ 0 │ 0 │ 0 │ 0 │ 0 │ 0 │
├───┼───┼───┼───┼───┼───┤
(empty)│ 0 │ 0 │ 0 │ 0 │ 0 │ 0 │
└───┴───┴───┴───┴───┴───┘
LCS = "hi" (length 2)Reading the table:
- Diagonal edges (↘) = letter match, add 1
- Horizontal/vertical edges (→ or ↓) = skip one letter, take max
Parent Pointers for Reconstruction
To recover the actual LCS (not just its length), track which choice was made:
def lcs_with_reconstruction(A, B):
m, n = len(A), len(B)
L = [[0] * (n + 1) for _ in range(m + 1)]
parent = {}
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if A[i] == B[j]:
L[i][j] = 1 + L[i + 1][j + 1]
parent[(i, j)] = ('match', i + 1, j + 1)
elif L[i + 1][j] >= L[i][j + 1]:
L[i][j] = L[i + 1][j]
parent[(i, j)] = ('skip_A', i + 1, j)
else:
L[i][j] = L[i][j + 1]
parent[(i, j)] = ('skip_B', i, j + 1)
# Reconstruct LCS by following parent pointers
lcs_result = []
i, j = 0, 0
while i < m and j < n:
action, ni, nj = parent[(i, j)]
if action == 'match':
lcs_result.append(A[i])
i, j = ni, nj
return L[0][0], ''.join(lcs_result)Example 2: Longest Increasing Subsequence (LIS)
Problem Definition
Given a sequence A, find the longest subsequence that is strictly increasing.
Example:
A = "carbohydrate"
LIS = "abort" (a < b < o < r < t)First Attempt (Fails!)
Subproblems: L(i) = LIS of suffix A[i:]
Relation: L(i) = max(L(i+1), # skip A[i]
1 + L(i+1)) # include A[i]Problem: No way to enforce "increasing"! When we include A[i], we don't know what the next included element will be, so we can't check if A[i] < next element.
The Fix: Add a Constraint
Key insight: We need to know where the LIS starts so we can compare elements.
Subproblems: L(i) = LIS of suffix A[i:] that STARTS WITH A[i]
(i.e., A[i] must be included as the first element)
n + 1 subproblemsThis constraint lets us enforce increasing: we know A[i] is first, so we can check A[i] < A[j] for the next element.
SRTBOT Solution
Subproblems: L(i) = length of LIS of A[i:] that starts with A[i]
for i ∈ {0, ..., n}
n + 1 subproblems
Relation: L(i) = 1 + max({ L(j) : i < j ≤ n, A[i] < A[j] } ∪ {0})
Translation:
- We include A[i] (that's the "1 +")
- Try all possible next elements j where:
- j comes after i (i < j)
- A[j] > A[i] (strictly increasing)
- Take max, or 0 if no valid j exists
Topological: for i = n down to 0:
compute L(i)
Base Case: L(n) = 0 # Empty suffix
Original: max(L(i) for i in 0..n-1)
(Don't know where LIS starts, so try all starting points)
Time: O(n) subproblems × O(n) work per subproblem = O(n²)Why Original Problem is max(L(i))?
The constraint "starts with A[i]" changes what L(i) computes:
- L(0) = LIS starting with first element (might not be optimal)
- L(5) = LIS starting with 6th element (might be optimal)
Since we don't know which starting point gives the longest LIS, we try all of them.
def lis(A):
n = len(A)
if n == 0:
return 0
# L[i] = length of LIS starting at index i
L = [1] * n # At minimum, each element is an LIS of length 1
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
if A[j] > A[i]:
L[i] = max(L[i], 1 + L[j])
return max(L)Visual Example: "empathy"
Sequence: e m p a t h y
Index: 0 1 2 3 4 5 6
Subproblem DAG (edges from i to j where A[i] < A[j]):
e ──→ m ──→ p ──→ t ──→ y
│ │ │ ↑
│ │ └─────┘
│ └──────────→ t ──→ y
│ ↑
└──────────────────┘
(and more edges...)
LIS = "empty" (e < m < p < t < y), length 5Connection to Shortest Paths
LIS can be viewed as finding the longest path in a DAG:
- Vertices: positions 0 to n-1, plus a "base" vertex
- Edges: i → j if i < j and A[i] < A[j]
- Edge weights: 1 (or -1 for shortest path formulation)
Longest path = LIS. But writing the DP directly is simpler than constructing the graph and running DAG shortest paths.
Example 3: Alternating Coin Game
Problem Definition
Setup:
- n coins in a row with values v₀, v₁, ..., v_{n-1}
- Two players take turns (I go first)
- Each turn: take either the leftmost or rightmost remaining coin
- Goal: Maximize my total value
Example:
Coins: [5, 10, 100, 25]
Bad strategy: Take 25 (rightmost) → Opponent takes 100 → I lose
Good strategy:
- I take 5 (leftmost)
- Opponent takes 25 (either choice)
- I take 100
- Opponent takes 10
Result: I get 5 + 100 = 105, Opponent gets 25 + 10 = 35Why Substrings?
- Taking from left → removes prefix
- Taking from right → removes suffix
- After a few moves → arbitrary substring remains
Prefixes or suffixes alone won't work; we need substrings.
Subproblem Expansion: Adding a Player Parameter
Naive approach: X(i, j) = max value I can get from coins v[i..j]
Problem: After I move, it's the opponent's turn. The recurrence needs to handle whose turn it is.
Solution: Add a parameter for the current player.
X(i, j, me) = max value I get from v[i..j] when I move first
X(i, j, you) = max value I get from v[i..j] when opponent moves firstSRTBOT Solution
Subproblems: X(i, j, P) = max value I get from coins v[i..j]
when player P moves first
P ∈ {me, you}
2 × O(n²) = O(n²) subproblems
Relations:
X(i, j, me) = max(
v[i] + X(i+1, j, you), # I take left coin
v[j] + X(i, j-1, you) # I take right coin
)
X(i, j, you) = min(
X(i+1, j, me), # Opponent takes left
X(i, j-1, me) # Opponent takes right
)
Note: When opponent moves, I don't add v[i] or v[j]
(opponent gets those points, not me)
Topological: Increasing substring length (j - i)
for length = 0 to n-1:
for i = 0 to n-1-length:
j = i + length
compute X(i, j, me) and X(i, j, you)
Base Cases: X(i, i, me) = v[i] # One coin, I take it
X(i, i, you) = 0 # One coin, opponent takes it
Original: X(0, n-1, me)
Time: O(n²) subproblems × O(1) work = O(n²)Why min() for Opponent's Turn?
This is a zero-sum game: opponent's gain = my loss.
- When I move: I choose to maximize my score
- When opponent moves: They choose to maximize their score = minimize my score
From my perspective, opponent's move is the worst case for me.
def coin_game(v):
n = len(v)
if n == 0:
return 0
# X[i][j][p]: max value I get from v[i..j], p=0 means my turn, p=1 means opponent
X = [[[0, 0] for _ in range(n)] for _ in range(n)]
# Base cases: single coin
for i in range(n):
X[i][i][0] = v[i] # My turn: I take it
X[i][i][1] = 0 # Opponent's turn: they take it, I get 0
# Fill by increasing length
for length in range(1, n):
for i in range(n - length):
j = i + length
# My turn: maximize
X[i][j][0] = max(
v[i] + X[i + 1][j][1], # Take left
v[j] + X[i][j - 1][1] # Take right
)
# Opponent's turn: minimize my score
X[i][j][1] = min(
X[i + 1][j][0], # They take left
X[i][j - 1][0] # They take right
)
return X[0][n - 1][0]Visual Example: [5, 10, 100, 25]
Subproblem grid (showing X[i][j][me] / X[i][j][you]):
j=0 j=1 j=2 j=3
i=0 5/0 10/5 105/10 105/35
i=1 - 10/0 100/10 100/35
i=2 - - 100/0 100/25
i=3 - - - 25/0
Answer: X[0][3][me] = 105
Optimal play:
1. I take 5 (left) → remaining [10, 100, 25]
2. Opp takes 25 (right) → remaining [10, 100]
3. I take 100 (right) → remaining [10]
4. Opp takes 10 → done
My total: 5 + 100 = 105Key Concept: Subproblem Constraints and Expansion
Subproblem Constraints
Sometimes the "obvious" subproblems don't work. Add constraints to make recurrences possible.
| Problem | Obvious Subproblem | Constraint Added |
|---|---|---|
| LIS | LIS of suffix A[i:] | LIS that starts with A[i] |
| Coin Game | Max value from v[i..j] | Max value when player P moves |
Subproblem Expansion
Adding constraints multiplies the number of subproblems:
| Expansion Type | Factor | Example |
|---|---|---|
| Binary choice | ×2 | Player ∈ {me, you} |
| Linear choice | ×n | Starting position ∈ {0, ..., n-1} |
| Quadratic | ×n² | Pair of positions |
As long as total subproblems stay polynomial, we get polynomial time.
When to Expand?
Expand when you can't write a recurrence because:
- You need information that isn't captured in current subproblems
- The "state" of the problem changes (e.g., whose turn)
- You need to enforce constraints (e.g., increasing order)
Ask: "What additional information would let me reduce to smaller subproblems?"
Parent Pointers: Recovering Solutions
DP computes optimal values, but often we want the actual solution.
General Technique
- During DP computation, record which choice led to the optimal value
- After computing, trace back through these "parent pointers"
# During computation
if choice_A_value > choice_B_value:
dp[i] = choice_A_value
parent[i] = ('A', next_subproblem_A)
else:
dp[i] = choice_B_value
parent[i] = ('B', next_subproblem_B)
# Reconstruction
def reconstruct(start):
result = []
current = start
while current is not base_case:
choice, next_sub = parent[current]
result.append(choice)
current = next_sub
return resultExamples
| Problem | Parent Pointer Records | Reconstruction Gives |
|---|---|---|
| LCS | Match vs Skip A vs Skip B | Actual common subsequence |
| LIS | Which j was chosen as next element | Actual increasing subsequence |
| Coin Game | Left vs Right choice | Optimal strategy |
| Shortest Path | Which edge was used | Actual path |
Summary
| Problem | Subproblems | Key Insight | Time |
|---|---|---|---|
| LCS | Pairs of suffixes (i, j) | Product of subproblem spaces for multiple sequences | O(nm) |
| LIS | Suffixes with constraint "starts at i" | Add constraint to enable comparison | O(n²) |
| Coin Game | Substrings × player | Expand subproblems for game state | O(n²) |
Key Techniques Introduced
- Multiple sequences: Multiply subproblem spaces
- Subproblem constraints: Add requirements to enable recurrences
- Subproblem expansion: Add parameters (player, starting point, etc.)
- Parent pointers: Track choices to reconstruct solutions
- Min-max for games: Maximize when you move, minimize when opponent moves
Choosing Subproblem Type
Single sequence:
- Try suffixes or prefixes first (O(n) subproblems)
- If that fails, try substrings (O(n²) subproblems)
- If still stuck, add constraints/parameters
Multiple sequences:
- Take product of individual subproblem spaces
- (suffixes of A) × (suffixes of B) for two sequencesNext Lecture
- More subproblem expansion examples
- Multiplying subproblems by n or n²
- More sophisticated constraint patterns