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 needs . So computing in increasing order of guarantees that line 5 below only ever reads entries that are already final.
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 , the entries hold the optimal revenues . It holds initially (), and the iteration for evaluates the recurrence using only entries covered by the invariant, so afterwards is optimal too. At termination all entries up to are optimal.
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 candidates the inner loop compares. For the candidates are , , and , and the winner is the middle one, two pieces of length 2. For the last candidate, the uncut rod, wins with 19.
Running time
The inner loop runs times in iteration , so there are exactly inner steps, and the algorithm takes time and 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.
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 per unit, the best rate, so long rods are cut mostly into fives and whenever 5 divides .
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 means " needs ", 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 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 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.
#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 quadruples the work.
Test yourself
In which order does bottom-up rod cutting fill its table, and why is that order valid?
- Longest rod first, because the answer is needed first
- Shortest rod first, because depends only on
- Any order, because the entries are independent
- Random order, to avoid bad cases
How many inner-loop steps does BOTTOM-UP-CUT-ROD take for ?
Which is an advantage of top-down memoization over the bottom-up table?
- It always uses less memory
- It solves only the subproblems reachable from the original question
- It avoids recursion
- It has a smaller asymptotic running time on every problem