TExcelTAD

Bottom-Up Dynamic Programming

Memoization keeps the recursion and lets the program discover which subproblems it needs. The bottom-up method turns that around: you decide in advance an order in which every subproblem's ingredients are ready before the subproblem itself, and you fill a table in that order with plain loops. No recursion, no "unknown" markers, no stack depth. For rod cutting the order is obvious, shortest rod first, and the whole algorithm is two nested loops. This lesson writes it, counts its steps exactly and compares the two styles.

The procedure

Solving length jj needs r0,…,rj−1r_0, \ldots, r_{j-1}. So computing r0,r1,r2,…r_0, r_1, r_2, \ldots in increasing order of jj guarantees that line 5 below only ever reads entries that are already final.

text
BOTTOM-UP-CUT-ROD(p, n)
1  r = new array [0..n]
2  r[0] = 0
3  for j = 1 to n                 // subproblems in increasing size
4      best = -infinity
5      for i = 1 to j             // first piece of length i
6          best = max(best, p[i - 1] + r[j - i])
7      r[j] = best
8  return r[n]

Correctness, as a loop invariant for the outer loop: at the start of the iteration for jj, the entries r[0],…,r[j−1]r[0], \ldots, r[j-1] hold the optimal revenues r0,…,rj−1r_0, \ldots, r_{j-1}. It holds initially (r[0]=0r[0] = 0), and the iteration for jj evaluates the recurrence max⁡i(pi+rj−i)\max_i (p_i + r_{j-i}) using only entries covered by the invariant, so afterwards r[j]r[j] is optimal too. At termination all entries up to nn are optimal.

python · try it yourself
prices = [2, 6, 9, 11, 15, 19, 20, 24]

def bottom_up_cut_rod(p, n):
    r = [0] * (n + 1)
    steps = 0
    for j in range(1, n + 1):
        best = float("-inf")
        for i in range(1, j + 1):
            steps += 1
            best = max(best, p[i - 1] + r[j - i])
        r[j] = best
        print(f"r[{j}] = {best:2}   candidates p_i + r[j-i]: {[p[i - 1] + r[j - i] for i in range(1, j + 1)]}")
    return r[n], steps

best, steps = bottom_up_cut_rod(prices, 8)
print("best revenue:", best, " inner steps:", steps)
r[1] =  2   candidates p_i + r[j-i]: [2]
r[2] =  6   candidates p_i + r[j-i]: [4, 6]
r[3] =  9   candidates p_i + r[j-i]: [8, 8, 9]
r[4] = 12   candidates p_i + r[j-i]: [11, 12, 11, 11]
r[5] = 15   candidates p_i + r[j-i]: [14, 15, 15, 13, 15]
r[6] = 19   candidates p_i + r[j-i]: [17, 18, 18, 17, 17, 19]
r[7] = 21   candidates p_i + r[j-i]: [21, 21, 21, 20, 21, 21, 20]
r[8] = 25   candidates p_i + r[j-i]: [23, 25, 24, 23, 24, 25, 22, 24]
best revenue: 25  inner steps: 36

Each line lists the jj candidates the inner loop compares. For j=4j = 4 the candidates are 2+92 + 9, 6+66 + 6, 9+29 + 2 and 11+011 + 0, and the winner is the middle one, two pieces of length 2. For j=6j = 6 the last candidate, the uncut rod, wins with 19.

Running time

The inner loop runs jj times in iteration jj, so there are exactly ∑j=1nj=n(n+1)2\sum_{j=1}^{n} j = \frac{n(n+1)}{2} inner steps, and the algorithm takes Θ(n2)\Theta(n^2) time and Θ(n)\Theta(n) space. That is the same asymptotic cost as memoization. The constant factor is usually better, because a loop step is cheaper than a function call plus a table check.

python · try it yourself
def bottom_up_cut_rod(p, n):
    r = [0] * (n + 1)
    for j in range(1, n + 1):
        best = 0
        for i in range(1, j + 1):
            v = p[i - 1] + r[j - i]
            if v > best:
                best = v
        r[j] = best
    return r

prices = [3 * L - 1 + 3 * (L % 5 == 0) for L in range(1, 1501)]
r = bottom_up_cut_rod(prices, 1500)
print("r[1500] =", r[1500], " inner steps:", 1500 * 1501 // 2)
print("revenue per unit length for n = 1..12:", [round(r[n] / n, 2) for n in range(1, 13)])
r[1500] = 5100  inner steps: 1125750
revenue per unit length for n = 1..12: [2.0, 2.5, 2.67, 2.75, 3.4, 3.17, 3.14, 3.12, 3.11, 3.4, 3.27, 3.25]

Length 1500 is out of reach for the memoized recursion in Python (the recursion limit) and for the naive one in any language, yet the loops finish in a moment with about 1.1 million steps. The per-unit revenue shows the structure of this price list: pieces of length 5 earn 175=3.4\frac{17}{5} = 3.4 per unit, the best rate, so long rods are cut mostly into fives and rn=3.4nr_n = 3.4 n whenever 5 divides nn.

The order of evaluation, in general

Bottom-up DP requires an order of the subproblems in which every subproblem comes after all the subproblems it depends on. In the language of the subproblem graph, where an edge x→yx \to y means "xx needs yy", that is a reverse topological order of the graph. Such an order exists exactly when the graph has no cycle. For rod cutting, "increasing length" is one; for the two-dimensional tables in later lessons it will be "row by row", "by increasing interval length" or "by increasing prefix length". Finding the order is part of designing the algorithm, and for some problems the natural parameterisation has no valid order at all, which is a sign the subproblems were chosen wrongly (Optimal Substructure has an example).

Top-down or bottom-up?

top-down (memoized) bottom-up (tabulated)
code the recurrence, plus a cache loops in a chosen order
subproblems solved only those reachable from the question all of them, reachable or not
order of evaluation found automatically by the recursion must be designed by you
overhead a call and a lookup per edge a loop step per edge
deep chains recursion depth ≈\approx longest path in the subproblem graph no recursion
saving memory hard: the cache must keep everything often easy: keep only the rows still needed

Both have the same asymptotic running time whenever every subproblem is reachable, which is the common case. In practice, memoization is the quick way to get a correct program from a recurrence, and bottom-up is how the final version is usually written. The DSA course shows both styles on Fibonacci numbers and grid paths in Tabulation.

Note: "Saving memory" matters a great deal for two-dimensional tables. The edit distance lesson computes its answer in O(min⁡(m,n))O(\min(m, n)) space by keeping just two rows, something a memoized version cannot do.

In C++

The bottom-up table in C++, with the same price list and the same lengths as above. Revenues stay small, so int is enough for the table; the step counter is a long long because a run only a few times longer than the one below would overflow 32 bits.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <vector>

std::vector<int> bottom_up_cut_rod(const std::vector<int>& p, int n, long long& steps) {
    std::vector<int> r(n + 1, 0);
    for (int j = 1; j <= n; ++j) {
        int best = 0;
        for (int i = 1; i <= j; ++i) {
            ++steps;
            best = std::max(best, p[i - 1] + r[j - i]);
        }
        r[j] = best;
    }
    return r;
}

int main() {
    std::vector<int> small = {2, 6, 9, 11, 15, 19, 20, 24};
    long long steps = 0;
    auto r = bottom_up_cut_rod(small, 8, steps);
    std::printf("r =");
    for (int x : r) std::printf(" %d", x);
    std::printf("  (%lld steps)\n", steps);

    std::vector<int> big;
    for (int L = 1; L <= 20000; ++L) big.push_back(3 * L - 1 + 3 * (L % 5 == 0));
    steps = 0;
    auto R = bottom_up_cut_rod(big, 20000, steps);
    std::printf("r[20000] = %d  (%lld steps)\n", R[20000], steps);
}
r = 0 2 6 9 12 15 19 21 25  (36 steps)
r[20000] = 68000  (200010000 steps)

Two hundred million loop steps for length 20,000 take a fraction of a second in C++. The quadratic growth is still there: doubling nn quadruples the work.

Test yourself

In which order does bottom-up rod cutting fill its table, and why is that order valid?

  1. Longest rod first, because the answer is needed first
  2. Shortest rod first, because rjr_j depends only on r0,…,rj−1r_0, \ldots, r_{j-1}
  3. Any order, because the entries are independent
  4. Random order, to avoid bad cases

How many inner-loop steps does BOTTOM-UP-CUT-ROD take for n=20n = 20?

  1. 2020
  2. 190190
  3. 210210
  4. 400400

Which is an advantage of top-down memoization over the bottom-up table?

  1. It always uses less memory
  2. It solves only the subproblems reachable from the original question
  3. It avoids recursion
  4. It has a smaller asymptotic running time on every problem