Lesson 5 · Dynamic programming

Rod Cutting Problem

Cut a rod into pieces to maximise total price. Every cut position splits the problem in two, and the same subproblems recur constantly.

Rod Cutting Problem concept diagramThe rod cutting table for length 8 with prices 1, 5, 8, 9, 10, 17, 17, 20. Rows show the price of each length, dp, the best revenue for each length (ending at 22), and the first cut chosen. Arrows trace the cuts backwards from 8 to 6 to 0, and the rod below is cut into pieces of length 2 and 6, worth 5 + 17 = 22.012345678lengthpricedpfirst cut–0–111552883910210132171761718120222cut 2cut 6rod of 82 → 56 → 175 + 17 = 22 = dp[8]dp[n] = max over i of price[i] + dp[n − i] · first cut stores the winning i
1

Prices, Pieces and the Search Space

Given a rod of length n and a price table where price[i] is what a piece of length i sells for, the task is the largest total revenue from cutting the rod into integer-length pieces.

Cuts are free and unlimited, pieces can repeat, and leaving the rod uncut is allowed. With n = 4 and prices [1, 5, 8, 9] for lengths 1 to 4, selling whole gives 9, but cutting into two 2s gives 10, the best answer.

The search space is large: a rod of length n has 2^(n−1) distinct cut patterns, one cut-or-not choice at each of the n−1 interior positions. Enumerating them is hopeless for even modest n.

  • Selling whole is one of the candidates – a first piece of length n leaves nothing, so the best revenue is never below price[n]
  • Prices need not grow with length – in the CLRS table lengths 6 and 7 both sell for 17, so a rod of 7 is worth more cut (18)
  • Prices that stop short of n – if pieces only go up to length L, the first-piece loop runs to min(j, L)
2

The Recurrence

  1. Base case – best(0) = 0, an empty rod earns nothing.
  2. Choose a first piece of length i, for every i from 1 to n.
  3. Recurse on the remaining length n − i.
  4. Take the maximum of price[i] + best(n − i) over all i.

The insight that collapses the search space: whatever the optimal cutting is, it has a first piece of some length i. The rest of the rod, length n−i, must itself be cut optimally, otherwise the whole could be improved.

The rod cutting recurrence follows directly: best(n) = max over i in 1..n of (price[i] + best(n − i)), with best(0) = 0.

Only one cut is chosen at each level; the recursion handles the rest, so no full cut pattern is ever listed. This is optimal substructure, the property that makes dynamic programming applicable at all.

  • Why only the first piece – the order of pieces does not change the revenue, so fixing the first one is enough to reach every multiset of pieces
  • The answer is a maximum, not a count – the recurrence finds the best revenue; how many cuttings achieve it is a different question
3

Why Plain Recursion Is Exponential

The recurrence is correct but catastrophically slow when evaluated directly.

best(4) calls best(3), best(2), best(1) and best(0). But best(3) also calls best(2) and best(1), and best(2) calls best(1) again. The same subproblems are recomputed along every path.

The number of calls satisfies T(n) = 1 + Σ T(j) for j from 0 to n − 1, which solves to T(n) = 2ⁿ. At n = 40 that is about a trillion calls for a problem with only 41 distinct answers.

This is overlapping subproblems, the second condition for dynamic programming. There are only n+1 distinct subproblems; the exponential cost is pure repetition.

  • Check the count – subtracting T(n−1) from T(n) gives T(n) = 2·T(n−1), and T(0) = 1, so T(8) = 256
  • Exponential time, shallow stack – the deepest chain cuts one unit at a time, so only n frames are live at once
Key reference

Terms, operations, and practical uses

Core vocabulary

  • best(j) / dp[j]The largest revenue for a rod of length j.
  • choice[j]The first piece that achieved dp[j]; used to rebuild the cuts.
  • Optimal substructureThe best cutting of n contains the best cutting of n − i.
  • Overlapping subproblemsThe same shorter lengths are needed by many longer ones.
Implementation

Code in Python, C++ and Java

PRICE = [0, 1, 5, 8, 9, 10, 17, 17, 20]   # PRICE[i] is the price of length i


def naive(n, calls):
    """Correct, and exponential - every subproblem is recomputed."""
    calls[0] += 1
    if n == 0:
        return 0
    return max(PRICE[i] + naive(n - i, calls) for i in range(1, n + 1))


def bottom_up(n):
    dp = [0] * (n + 1)
    choice = [0] * (n + 1)

    for length in range(1, n + 1):
        best = 0
        for first in range(1, length + 1):
            candidate = PRICE[first] + dp[length - first]
            if candidate > best:
                best = candidate
                choice[length] = first
        dp[length] = best

    return dp, choice


def cuts(choice, n):
    pieces = []
    while n > 0:
        pieces.append(choice[n])
        n -= choice[n]
    return pieces


def main():
    n = 8

    calls = [0]
    print(f"naive({n})      = {naive(n, calls)}   after {calls[0]} calls")

    dp, choice = bottom_up(n)
    print(f"bottom_up({n})  = {dp[n]}   after {n * (n + 1) // 2} inner steps\n")

    print("length   dp   first cut")
    for length in range(1, n + 1):
        print(f"{length:>6} {dp[length]:>4} {choice[length]:>11}")

    print(f"\npieces for length {n}: {cuts(choice, n)}")


if __name__ == "__main__":
    main()
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>

// PRICE[i] is the price of a piece of length i.
const std::vector<int> PRICE = {0, 1, 5, 8, 9, 10, 17, 17, 20};

// Correct, and exponential - every subproblem is recomputed.
int naive(int n, long& calls) {
    ++calls;
    if (n == 0) return 0;
    int best = 0;
    for (int i = 1; i <= n; ++i) best = std::max(best, PRICE[i] + naive(n - i, calls));
    return best;
}

std::pair<std::vector<int>, std::vector<int>> bottomUp(int n) {
    std::vector<int> dp(n + 1, 0);
    std::vector<int> choice(n + 1, 0);

    for (int length = 1; length <= n; ++length) {
        int best = 0;
        for (int first = 1; first <= length; ++first) {
            const int candidate = PRICE[first] + dp[length - first];
            if (candidate > best) {
                best = candidate;
                choice[length] = first;
            }
        }
        dp[length] = best;
    }
    return {dp, choice};
}

std::vector<int> cuts(const std::vector<int>& choice, int n) {
    std::vector<int> pieces;
    while (n > 0) {
        pieces.push_back(choice[n]);
        n -= choice[n];
    }
    return pieces;
}

int main() {
    const int n = 8;

    long calls = 0;
    std::cout << "naive(" << n << ")      = " << naive(n, calls)
              << "   after " << calls << " calls\n";

    auto [dp, choice] = bottomUp(n);
    std::cout << "bottom_up(" << n << ")  = " << dp[n]
              << "   after " << n * (n + 1) / 2 << " inner steps\n\n";

    std::cout << "length   dp   first cut\n";
    for (int length = 1; length <= n; ++length) {
        std::cout << std::setw(6) << length << std::setw(5) << dp[length]
                  << std::setw(12) << choice[length] << "\n";
    }

    std::cout << "\npieces for length " << n << ": [";
    const auto pieces = cuts(choice, n);
    for (size_t k = 0; k < pieces.size(); k++) std::cout << (k ? ", " : "") << pieces[k];
    std::cout << "]\n";
    return 0;
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    // PRICE[i] is the price of a piece of length i.
    private static final int[] PRICE = {0, 1, 5, 8, 9, 10, 17, 17, 20};
    private static long calls = 0;

    // Correct, and exponential - every subproblem is recomputed.
    private static int naive(int n) {
        calls++;
        if (n == 0) return 0;
        int best = 0;
        for (int i = 1; i <= n; i++) best = Math.max(best, PRICE[i] + naive(n - i));
        return best;
    }

    private static int[][] bottomUp(int n) {
        int[] dp = new int[n + 1];
        int[] choice = new int[n + 1];

        for (int length = 1; length <= n; length++) {
            int best = 0;
            for (int first = 1; first <= length; first++) {
                int candidate = PRICE[first] + dp[length - first];
                if (candidate > best) {
                    best = candidate;
                    choice[length] = first;
                }
            }
            dp[length] = best;
        }
        return new int[][] {dp, choice};
    }

    private static List<Integer> cuts(int[] choice, int n) {
        List<Integer> pieces = new ArrayList<>();
        while (n > 0) {
            pieces.add(choice[n]);
            n -= choice[n];
        }
        return pieces;
    }

    public static void main(String[] args) {
        int n = 8;

        System.out.printf("naive(%d)      = %d   after %d calls%n", n, naive(n), calls);

        int[][] r = bottomUp(n);
        int[] dp = r[0], choice = r[1];
        System.out.printf("bottom_up(%d)  = %d   after %d inner steps%n%n",
                n, dp[n], n * (n + 1) / 2);

        System.out.println("length   dp   first cut");
        for (int length = 1; length <= n; length++) {
            System.out.printf("%6d %4d %11d%n", length, dp[length], choice[length]);
        }

        System.out.printf("%npieces for length %d: %s%n", n, cuts(choice, n));
    }
}
Watch it run

Step through it

Running on prices 1, 5, 8, 9, 10, 17, 17, 20 for lengths 1 to 8

lengthpricebest revenuefirst cut0–11253849510617717820rodlength 8prices 1, 5, 8, 9, 10, 17, 17, 20
Step 1

A rod of 8 and a price for each length

Cuts are free, pieces may repeat, and selling the rod whole is allowed. The only goal is the largest total price. The dashed rows are what the method will fill: the best revenue for every length 0 to 8, and the first cut that achieves it.

Output
1 / 15
4

Memoization: The Smallest Possible Fix

The recursion is exponential only because it forgets. Keep an array memo[0..n] filled with a sentinel. At the top of the function, return memo[n] if it is already set; at the bottom, store the result before returning. Two added lines.

That collapses O(2ⁿ) to O(n²): each of the n+1 subproblems is computed once, and computing one costs O(n) because it tries every first cut. Space is O(n) for the table plus O(n) for the recursion stack.

Top-down (memoization) and bottom-up (tabulation) reach the same complexity. Memoization keeps the recursion's shape and computes only the subproblems it reaches; tabulation avoids the call stack and suits problems like this one, where every subproblem is needed anyway.

The same recurrence, three ways
ApproachTimeSpaceNote
Plain recursionO(2ⁿ)O(n) stackrecomputes constantly
MemoizedO(n²)O(n) + stacktwo added lines
TabulatedO(n²)O(n)no recursion at all
  • Pick a sentinel that is never an answer – use −1, because 0 is a real answer for length 0
  • Deep recursion still bites – Python's default limit of 1,000 frames stops a memoized version near n = 1,000; the table has no such limit
5

Bottom-Up DP and Recovering the Cuts

Solving lengths in increasing order means every subproblem a step needs is already computed. Build dp[0..n] where dp[j] is the best revenue for length j; each dp[j] tries all first pieces i ≤ j using the finished dp[j − i]. Two nested loops give O(n²) time and O(n) space.

The table gives the best revenue but not the cuts. Recovering them needs a second array: when dp[j] takes its maximum at length i, record choice[j] = i.

Reconstruction then walks backwards. Start at n, emit choice[n], move to n − choice[n], and repeat until zero. A value table plus a choice table is the standard way to recover any DP solution, not just this one. For length 8 with the CLRS prices the walk is 8 → 6 → 0, pieces 2 and 6, revenue 22.

  • Ties – keep the first maximiser (update only on a strict >) and the recovered cuts are the same on every run
  • Space cannot drop below O(n) – dp[j] reads every earlier entry, unlike Fibonacci-style recurrences that need only the last two
6

Rod Cutting vs Unbounded Knapsack

Rod cutting is the unbounded knapsack problem in disguise. A rod of length n is a knapsack of capacity n, a piece of length i is an item of weight i and value price[i], and pieces may repeat because items are unlimited. Spotting the disguise is usually what an interview is testing.

The one difference is leftover space. A knapsack may leave capacity unused; a rod never needs to, because a leftover stub can always be sold as a piece. Starting the table at 0 and taking maximums handles both. The coding version, with a cost per cut as a common variant, is on the rod cutting problem page.

  • Weight = length, value = price, capacity = n
  • 0/1 knapsack is different – each item at most once, which needs a second index or a backwards loop; see 0/1 knapsack