Angad Sandhu
Search
Browse
On this page

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:

  1. Integer subproblems - when input includes integers, consider smaller integers
  2. Pseudopolynomial time - a "pretty good" running time that depends on input values
  3. Rod Cutting - partitioning for maximum value
  4. Subset Sum - decision problem with boolean DP
  5. 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

StepKey Techniques
S - SubproblemsSequences → prefixes/suffixes/substrings. Integers → smaller integers. Products for multiple inputs. Expansion with constraints.
R - RelationsIdentify a question about the solution. Locally brute force all answers. Guessing perspective: assume correct guess, pay by trying all.
T - Topological OrderEnsure acyclicity. Usually nested for loops.
B - Base CasesSmallest subproblems with known answers.
O - Original ProblemOne 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  ✓ OPTIMAL

Greedy "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], pieces

Subproblem 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, subset

Subproblem 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:

  1. The input size (number of words), AND
  2. The input values (magnitudes of integers)
Strongly Polynomial ⊂ Weakly Polynomial ⊂ Pseudopolynomial
        (best)                                    (still pretty good)
TypeRunning Time Polynomial In
Strongly polynomialInput size only
Weakly polynomialInput size + log(input values)
PseudopolynomialInput size + input values

Comparison

AlgorithmRunning TimeType
Rod CuttingO(L²)Polynomial (L is input size)
Subset SumO(nT)Pseudopolynomial
FibonacciO(n)Polynomial
Bellman-FordO(VE)Polynomial
Radix SortO(n · log_n(U))Weakly polynomial
Counting SortO(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

TypeExamples
Prefixes/SuffixesBowling, LCS, LIS, Subset Sum
SubstringsAlternating Coin Game, Parenthesization
IntegersFibonacci, Rod Cutting, Subset Sum, Bellman-Ford
VerticesDAG Shortest Paths, Bellman-Ford, Floyd-Warshall
ProductsLCS (two sequences), Floyd-Warshall (vertices × prefix)

By Subproblem Expansion

TypeFactorExamples
No expansion×1Fibonacci, Bowling, LCS
Non-expansive constraint×1LIS (must start with aᵢ)
Constant expansion×2Coin Game (me/you), Parenthesization (min/max)
Small expansion×FPiano Fingering (F fingers)
Linear expansion×nBellman-Ford (edge count)

By Branching Factor

BranchingExamples
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

MethodExamples
Take best (min/max)Most optimization problems
AddFibonacci
Concatenate pathsFloyd-Warshall
Combine with operatorParenthesization (+ or ×)
OR (any)Subset Sum

By Original Problem

TypeExamples
Single subproblemFibonacci, Bowling, LCS, Coin Game, Parenthesization, Rod Cutting, Subset Sum
All subproblemsDAG Shortest Paths, Bellman-Ford, Floyd-Warshall
Max over subproblemsLIS

Summary: The Four DP Lectures

LectureFocusKey Examples
15SRTBOT framework, memoization, sequence subproblemsFibonacci, DAG Shortest Paths, Bowling
16Multiple sequences, substrings, parent pointersLCS, LIS, Alternating Coin Game
17Subproblem expansion, constraints, stateBellman-Ford, Floyd-Warshall, Parenthesization, Piano Fingering
18Integer subproblems, pseudopolynomial time, decision problemsRod Cutting, Subset Sum

Key Takeaways

  1. Subproblems: The hardest part. Try prefixes/suffixes/substrings for sequences, smaller values for integers.

  2. Relations: Identify a question, brute force all answers. "Guessing" perspective helps.

  3. Expansion: Add parameters to track state when needed. Keep polynomial count.

  4. Pseudopolynomial: Running time depending on input values (not just size) is "pretty good" when values are small.

  5. Decision vs Optimization: Use OR instead of min/max for yes/no problems.

  6. 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).

Browse the library