18. Dynamic Programming, Part 4: Pseudopolynomial Time, Rod Cutting, Subset Sum
18. Dynamic Programming, Part 4: Pseudopolynomial Time, Rod Cutting, Subset Sum
Overview
This lecture concludes the DP series by exploring:
- Integer subproblems - when input includes integers, consider smaller integers
- Pseudopolynomial time - a "pretty good" running time that depends on input values
- Rod Cutting - partitioning for maximum value
- Subset Sum - decision problem with boolean DP
- Characterization - review of all DP techniques seen in the course
Key insight: Some problems have running times that depend on the magnitude of input numbers, not just the count of inputs. This leads to pseudopolynomial algorithms.
SRTBOT Review
| Step | Key Techniques |
|---|---|
| S - Subproblems | Sequences → prefixes/suffixes/substrings. Integers → smaller integers. Products for multiple inputs. Expansion with constraints. |
| R - Relations | Identify a question about the solution. Locally brute force all answers. Guessing perspective: assume correct guess, pay by trying all. |
| T - Topological Order | Ensure acyclicity. Usually nested for loops. |
| B - Base Cases | Smallest subproblems with known answers. |
| O - Original Problem | One or more subproblems combined. |
| T - Time | Σ(work per subproblem) ≤ (# subproblems) × (max work) + (original problem work) |
Integer Subproblems
When input includes an integer K:
- Natural subproblems: solve for all integers 0, 1, ..., K
- Similar to how sequences use prefixes/suffixes
- Example: Fibonacci - given n, solve F(0), F(1), ..., F(n)
Example 1: Rod Cutting
Problem Definition
Given:
- A rod of integer length L
- Value function v(ℓ) = price for selling a rod of length ℓ (for ℓ = 1, 2, ..., L)
Goal: Cut the rod into pieces to maximize total selling price.
This is finding the maximum value partition of L into positive integers.
Example
L = 7
Length ℓ: 1 2 3 4 5 6 7
Value v(ℓ): $1 $10 $13 $18 $20 $31 $32
Option 1: Sell whole rod (length 7)
Value = $32
Option 2: Sell 6 + 1
Value = $31 + $1 = $32
Option 3: Sell 3 + 4
Value = $13 + $18 = $31 (worse!)
Option 4: Sell 3 + 2 + 2
Value = $13 + $10 + $10 = $33 ✓ OPTIMALGreedy "bang for buck" fails! The ratio v(ℓ)/ℓ is maximized at ℓ=6 (ratio ≈ 5.17), but the optimal doesn't use length 6.
SRTBOT Solution
Key question: What is the length of the first piece we cut and sell?
If we cut a piece of length p, the remaining problem is the same with length L - p.
Subproblems: x(ℓ) = max value partition of a rod of length ℓ
for ℓ ∈ {0, 1, ..., L}
L + 1 subproblems
Relation: x(ℓ) = max over p ∈ {1, ..., ℓ}:
v(p) + x(ℓ - p)
(Guess first piece length p, get its value, recurse on remainder)
Topological: Increasing ℓ (ℓ = 0, 1, ..., L)
Always recurse to smaller ℓ (since p ≥ 1)
Base Case: x(0) = 0 (no rod = no value)
Original: x(L)
Time: O(L) subproblems × O(L) work = O(L²)Implementation
def rod_cutting(L, v):
"""
L: rod length
v: list where v[p] = value of piece of length p (1-indexed, v[0] unused)
"""
# x[l] = max value for rod of length l
x = [0] * (L + 1)
parent = [0] * (L + 1) # For reconstruction
for l in range(1, L + 1):
for p in range(1, l + 1):
if v[p] + x[l - p] > x[l]:
x[l] = v[p] + x[l - p]
parent[l] = p
# Reconstruct solution
pieces = []
remaining = L
while remaining > 0:
pieces.append(parent[remaining])
remaining -= parent[remaining]
return x[L], piecesSubproblem DAG Visualization
The DAG is a complete graph on vertices {0, 1, ..., L}:
0 ←── 1 ←── 2 ←── 3 ←── 4 ←── 5 ←── 6 ←── 7
│ │ │ │ │ │ │
└─────┴─────┴─────┴─────┴─────┴─────┘
(edges go from each vertex to all smaller vertices)
Edge from ℓ to ℓ-p has weight v(p).
Finding max value = finding longest path from 0 to L.Is O(L²) Polynomial Time?
Yes! Here's why:
Input size = L + 1 words (the length L plus L values)
Running time = O(L²) = O((input size)²)
This is polynomial in the input size, so rod cutting is a polynomial time algorithm.
Example 2: Subset Sum
Problem Definition
Given:
- A multiset A = {a₀, a₁, ..., aₙ₋₁} of n positive integers
- A target sum T
Goal: Does any subset S ⊆ A sum to exactly T?
This is a decision problem (yes/no answer), not an optimization problem.
Example
A = {2, 5, 7, 8, 9}
T = 21: YES (5 + 7 + 9 = 21)
T = 25: NO (no subset sums to 25)Key Insight: Boolean DP
Unlike optimization problems that use min/max, decision problems use OR (any):
- If ANY way to achieve the goal exists, answer is YES
- We combine subproblem answers with OR instead of min/max
SRTBOT Solution
Key question: Is a₀ in the subset S?
- If NO: Need subset of {a₁, ..., aₙ₋₁} summing to T
- If YES: Need subset of {a₁, ..., aₙ₋₁} summing to T - a₀
Subproblems: x(i, t) = does any subset of {aᵢ, ..., aₙ₋₁} sum to t?
for i ∈ {0, ..., n}, t ∈ {0, ..., T}
(n + 1) × (T + 1) subproblems
Relation: x(i, t) = x(i+1, t) # Don't include aᵢ
OR
x(i+1, t - aᵢ) if aᵢ ≤ t # Include aᵢ
Topological: Decreasing i (i = n, n-1, ..., 0)
(t can be in any order, only i matters)
Base Cases: x(n, 0) = True (empty set sums to 0)
x(n, t) = False for t > 0 (empty set can't sum to positive)
Original: x(0, T)
Time: O(nT) subproblems × O(1) work = O(nT)Implementation
def subset_sum(A, T):
"""
A: list of positive integers
T: target sum
Returns: (bool, list) - whether possible and which elements
"""
n = len(A)
# x[i][t] = can we sum to t using A[i:]?
x = [[False] * (T + 1) for _ in range(n + 1)]
parent = [[None] * (T + 1) for _ in range(n + 1)]
# Base case: empty suffix
x[n][0] = True
# Fill table
for i in range(n - 1, -1, -1):
for t in range(T + 1):
# Option 1: Don't include A[i]
if x[i + 1][t]:
x[i][t] = True
parent[i][t] = ('skip', i + 1, t)
# Option 2: Include A[i] (if possible)
if A[i] <= t and x[i + 1][t - A[i]]:
x[i][t] = True
parent[i][t] = ('take', i + 1, t - A[i])
# Reconstruct solution
if not x[0][T]:
return False, []
subset = []
i, t = 0, T
while i < n and t > 0:
action, ni, nt = parent[i][t]
if action == 'take':
subset.append(A[i])
i, t = ni, nt
return True, subsetSubproblem DAG Visualization
Example: A = {3, 4, 3, 1}, T = 6
t=0 t=1 t=2 t=3 t=4 t=5 t=6
i=4 Y N N N N N N (base case)
↑ ↑ ↑ ↑ ↑ ↑ ↑
i=3 Y Y N N N N N (can make 0 or 1)
↑ ╱↑ ╱↑ ╱↑ ╱↑ ╱↑ ╱
i=2 Y Y N Y Y N N (can make 0,1,3,4)
↑ ╱ ↑ ╱ ↑ ╱ ↑ ╱ ↑ ╱ ↑ ╱
i=1 Y Y N Y Y Y N (can make 0,1,3,4,5)
↑╱ ↑╱ ↑╱ ↑╱ ↑╱ ↑╱ ↑╱
i=0 Y Y N Y Y Y Y (can make 0,1,3,4,5,6)
Vertical edges: skip element (t unchanged)
Diagonal edges: take element (t decreases by aᵢ)
Answer: x[0][6] = Y (can make 6 = 3 + 3)Pseudopolynomial Time
Is O(nT) Polynomial?
No! Here's why:
Input size = n + 1 words (n integers in A, plus T)
Running time = O(nT)
But T is not bounded by the input size! T is an input value, not an input count.
The Problem with Input Values
In the Word RAM model:
- Each integer fits in a w-bit word
- So T ≤ 2^w
- We assume w ≥ log n (to index arrays)
- But w could be much larger than log n!
Example: If w = n (n-bit numbers), then T could be 2^n, making O(nT) = O(n · 2^n) = exponential!
Definition: Pseudopolynomial Time
An algorithm runs in pseudopolynomial time if its running time is polynomial in:
- The input size (number of words), AND
- The input values (magnitudes of integers)
Strongly Polynomial ⊂ Weakly Polynomial ⊂ Pseudopolynomial
(best) (still pretty good)| Type | Running Time Polynomial In |
|---|---|
| Strongly polynomial | Input size only |
| Weakly polynomial | Input size + log(input values) |
| Pseudopolynomial | Input size + input values |
Comparison
| Algorithm | Running Time | Type |
|---|---|---|
| Rod Cutting | O(L²) | Polynomial (L is input size) |
| Subset Sum | O(nT) | Pseudopolynomial |
| Fibonacci | O(n) | Polynomial |
| Bellman-Ford | O(VE) | Polynomial |
| Radix Sort | O(n · log_n(U)) | Weakly polynomial |
| Counting Sort | O(n + U) | Pseudopolynomial |
When is Pseudopolynomial Good Enough?
Pseudopolynomial implies polynomial when input integers are polynomially bounded:
If all input integers ≤ n^c for some constant c,
then pseudopolynomial = polynomial.This is the same condition that makes:
- Radix sort run in O(n) time
- Counting sort run in O(n) time
- Direct access arrays efficient
Characterization of All DP Examples
By Subproblem Type
| Type | Examples |
|---|---|
| Prefixes/Suffixes | Bowling, LCS, LIS, Subset Sum |
| Substrings | Alternating Coin Game, Parenthesization |
| Integers | Fibonacci, Rod Cutting, Subset Sum, Bellman-Ford |
| Vertices | DAG Shortest Paths, Bellman-Ford, Floyd-Warshall |
| Products | LCS (two sequences), Floyd-Warshall (vertices × prefix) |
By Subproblem Expansion
| Type | Factor | Examples |
|---|---|---|
| No expansion | ×1 | Fibonacci, Bowling, LCS |
| Non-expansive constraint | ×1 | LIS (must start with aᵢ) |
| Constant expansion | ×2 | Coin Game (me/you), Parenthesization (min/max) |
| Small expansion | ×F | Piano Fingering (F fingers) |
| Linear expansion | ×n | Bellman-Ford (edge count) |
By Branching Factor
| Branching | Examples |
|---|---|
| Constant (2-3) | Fibonacci, Bowling, LCS, Coin Game, Floyd-Warshall, Subset Sum |
| O(degree) | DAG Shortest Paths, Bellman-Ford |
| O(n) | LIS, Parenthesization, Rod Cutting |
By Combination Method
| Method | Examples |
|---|---|
| Take best (min/max) | Most optimization problems |
| Add | Fibonacci |
| Concatenate paths | Floyd-Warshall |
| Combine with operator | Parenthesization (+ or ×) |
| OR (any) | Subset Sum |
By Original Problem
| Type | Examples |
|---|---|
| Single subproblem | Fibonacci, Bowling, LCS, Coin Game, Parenthesization, Rod Cutting, Subset Sum |
| All subproblems | DAG Shortest Paths, Bellman-Ford, Floyd-Warshall |
| Max over subproblems | LIS |
Summary: The Four DP Lectures
| Lecture | Focus | Key Examples |
|---|---|---|
| 15 | SRTBOT framework, memoization, sequence subproblems | Fibonacci, DAG Shortest Paths, Bowling |
| 16 | Multiple sequences, substrings, parent pointers | LCS, LIS, Alternating Coin Game |
| 17 | Subproblem expansion, constraints, state | Bellman-Ford, Floyd-Warshall, Parenthesization, Piano Fingering |
| 18 | Integer subproblems, pseudopolynomial time, decision problems | Rod Cutting, Subset Sum |
Key Takeaways
-
Subproblems: The hardest part. Try prefixes/suffixes/substrings for sequences, smaller values for integers.
-
Relations: Identify a question, brute force all answers. "Guessing" perspective helps.
-
Expansion: Add parameters to track state when needed. Keep polynomial count.
-
Pseudopolynomial: Running time depending on input values (not just size) is "pretty good" when values are small.
-
Decision vs Optimization: Use OR instead of min/max for yes/no problems.
-
DP = Shortest Paths: Many DPs reduce to finding paths in a DAG, but writing DP directly is often simpler.
Complexity Preview (Next Lecture)
Subset Sum is actually a famous NP-complete problem:
- No known polynomial time algorithm
- Pseudopolynomial O(nT) is the best known
- If T is exponential in n, the problem is hard
This connects DP to computational complexity theory—some problems are inherently hard, and pseudopolynomial is the best we can do (unless P = NP).