TExcelTAD

Top-Down Memoization

The naive rod-cutting recursion of the previous lesson made 2n2^n calls to answer n+1n + 1 distinct questions. The cure is almost embarrassingly simple: write each answer down the first time you compute it, and look it up every time after that. This is memoization (from "memo", a note to yourself, not "memorize"). The recursive structure of the program stays exactly the same; only a table and two lines are added. This lesson adds them, counts the calls exactly and shows where the top-down approach runs into a practical wall.

The memoized procedure

Keep an array memo[0..n]memo[0..n] whose entries start as "unknown". Before solving a subproblem, check the array; after solving it, store the result.

text
MEMO-CUT-ROD(p, n)
1  memo = new array [0..n], every entry UNKNOWN
2  return MEMO-AUX(p, n, memo)

MEMO-AUX(p, j, memo)
1  if memo[j] != UNKNOWN
2      return memo[j]               // answered before: no work
3  if j == 0
4      best = 0
5  else best = -infinity
6      for i = 1 to j
7          best = max(best, p[i - 1] + MEMO-AUX(p, j - i, memo))
8  memo[j] = best
9  return best

Correctness is inherited from the recurrence rj=max⁡1≤i≤j(pi+rj−i)r_j = \max_{1 \le i \le j} (p_i + r_{j-i}): line 1 only ever returns a value that lines 3 to 8 computed earlier for the same jj, and a subproblem's answer does not depend on who is asking for it.

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

def memo_cut_rod(p, n):
    memo = [None] * (n + 1)
    stats = {"calls": 0, "solved": 0, "order": []}

    def aux(j):
        stats["calls"] += 1
        if memo[j] is not None:
            return memo[j]
        stats["solved"] += 1
        best = 0 if j == 0 else max(p[i - 1] + aux(j - i) for i in range(1, j + 1))
        memo[j] = best
        stats["order"].append(j)          # the moment subproblem j is finished
        return best

    return aux(n), memo, stats

r, memo, stats = memo_cut_rod(prices, 8)
print("best revenue:", r)
print("memo table:  ", memo)
print("calls:", stats["calls"], " subproblems solved:", stats["solved"])
print("finished in the order:", stats["order"])
best revenue: 25
memo table:   [0, 2, 6, 9, 12, 15, 19, 21, 25]
calls: 37  subproblems solved: 9
finished in the order: [0, 1, 2, 3, 4, 5, 6, 7, 8]

Two observations. First, only 9 subproblems are ever solved, one per length 00 to 88, and the other calls are instant lookups. Second, look at the order in which subproblems are finished: 0,1,2,…,80, 1, 2, \ldots, 8. The top-down program dives straight to the bottom (the call for 8 calls 7, which calls 6, and so on down to 0) and completes the subproblems on the way back up, smallest first. It discovers by itself the order that the bottom-up method of the next lesson writes down explicitly.

Counting the work exactly

Each subproblem j≥1j \ge 1 is solved once, and solving it runs the loop of line 6 jj times, each iteration making one call. So the number of loop iterations is

∑j=1nj=n(n+1)2,\sum_{j=1}^{n} j = \frac{n(n+1)}{2},

and the number of calls is that plus the initial call: 1+n(n+1)21 + \frac{n(n+1)}{2}. Every call does O(1)O(1) work besides its loop, so the running time is Θ(n2)\Theta(n^2), down from Θ(2n)\Theta(2^n).

python · try it yourself
calls = 0

def memo_cut_rod(p, n):
    memo = [None] * (n + 1)
    def aux(j):
        global calls
        calls += 1
        if memo[j] is None:
            best = 0
            for i in range(1, j + 1):
                best = max(best, p[i - 1] + aux(j - i))
            memo[j] = best
        return memo[j]
    return aux(n)

# a longer price list: 3 per unit, minus 1, but lengths divisible by 5 earn a bonus
prices = [3 * L - 1 + 3 * (L % 5 == 0) for L in range(1, 151)]
for n in [8, 20, 60, 150]:
    calls = 0
    r = memo_cut_rod(prices, n)
    print(f"n = {n:3}: revenue {r:4}, calls {calls:6}, 1 + n(n+1)/2 = {1 + n * (n + 1) // 2:6}")
n =   8: revenue   25, calls     37, 1 + n(n+1)/2 =     37
n =  20: revenue   68, calls    211, 1 + n(n+1)/2 =    211
n =  60: revenue  204, calls   1831, 1 + n(n+1)/2 =   1831
n = 150: revenue  510, calls  11326, 1 + n(n+1)/2 =  11326

The formula is exact. For n=150n = 150 the memoized program makes 11,326 calls; the naive one would make 21502^{150}, a number with 46 digits.

The subproblem graph

A good way to picture any dynamic program is its subproblem graph: one vertex per distinct subproblem and a directed edge from xx to yy when solving xx directly needs the answer to yy. For rod cutting, vertex jj has edges to j−1,j−2,…,0j - 1, j - 2, \ldots, 0:

text
 8 --> 7 --> 6 --> 5 --> 4 --> 3 --> 2 --> 1 --> 0
  \_____^     ... and every longer jump j --> k for k < j ...

So the graph has n+1n + 1 vertices and n(n+1)2\frac{n(n+1)}{2} edges. The recursion tree of the naive algorithm is what you get by unfolding this graph into a tree, copying a vertex every time it is reached by a different path. Memoization walks the graph instead of the tree: each vertex is expanded once, and each edge is followed once. That gives a general rule worth remembering:

The running time of a memoized (or bottom-up) dynamic program is proportional to the number of vertices plus the number of edges of its subproblem graph, times the work per edge.

The graph must be acyclic. If subproblem xx needed yy and yy needed xx, the recursion would never finish. The lesson Overlapping Subproblems and the Subproblem Graph uses this picture to analyse several problems at once.

Memoization with a library decorator

Python's functools.cache does the bookkeeping for you: it stores results in a dictionary keyed by the arguments. It is the fastest way to turn a correct recurrence into a usable program, as long as the arguments are hashable.

python · try it yourself
from functools import cache
import sys

prices = [3 * L - 1 + 3 * (L % 5 == 0) for L in range(1, 151)]
depth = deepest = 0

@cache
def r(j):
    global depth, deepest
    depth += 1
    deepest = max(deepest, depth)
    best = 0
    for i in range(1, j + 1):
        best = max(best, prices[i - 1] + r(j - i))
    depth -= 1
    return best

print("r(150) =", r(150))
print("cache info:", r.cache_info())
print("deepest recursion:", deepest, "calls of r; Python's limit:", sys.getrecursionlimit(), "frames")
r(150) = 510
cache info: CacheInfo(hits=11175, misses=151, maxsize=None, currsize=151)
deepest recursion: 151 calls of r; Python's limit: 1000 frames

Here is the practical wall. The first call for length nn goes n+1n + 1 levels deep before anything is stored (the chain n→n−1→⋯→0n \to n - 1 \to \cdots \to 0), and Python refuses to go beyond its recursion limit: in desktop Python, r(5000) raises RecursionError. You can raise the limit, but deep recursion is slow, and once the underlying C stack (or, in the browser, the JavaScript stack) runs out, the interpreter crashes instead of raising an error. The bottom-up formulation avoids recursion entirely. Notice also hits=... in the cache info: those are the lookups that the naive program would have answered by recomputing.

In C++

The same memoized recursion with a std::vector as the memo, −1-1 meaning unknown (revenues are never negative). C++ has a much larger default stack than Python's recursion limit, so depth a few thousand is fine; at depth in the millions it would still overflow.

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

long long calls = 0;

int aux(const std::vector<int>& p, int j, std::vector<int>& memo) {
    ++calls;
    if (memo[j] >= 0) return memo[j];
    int best = 0;
    for (int i = 1; i <= j; ++i)
        best = std::max(best, p[i - 1] + aux(p, j - i, memo));
    memo[j] = best;
    return best;
}

int memo_cut_rod(const std::vector<int>& p, int n) {
    std::vector<int> memo(n + 1, -1);
    return aux(p, n, memo);
}

int main() {
    std::vector<int> prices;
    for (int L = 1; L <= 3000; ++L) prices.push_back(3 * L - 1 + 3 * (L % 5 == 0));
    for (int n : {8, 100, 3000}) {
        calls = 0;
        int r = memo_cut_rod(prices, n);
        std::printf("n = %4d: revenue %5d, calls %lld\n", n, r, calls);
    }
}
n =    8: revenue    25, calls 37
n =  100: revenue   340, calls 5051
n = 3000: revenue 10200, calls 4501501

The call counts match 1+n(n+1)21 + \frac{n(n+1)}{2} again: 37, 5051 and 4,501,501.

When top-down wins

Memoization has one advantage over the bottom-up table: it only solves the subproblems that are actually reachable from the original question. For rod cutting every length is reachable, so there is no saving. But consider a variant where pieces may only have lengths from a small set, say {5,7}\{5, 7\}: from n=40n = 40 only lengths 40−5a−7b40 - 5a - 7b appear, and a memoized program touches just those, while a bottom-up table fills all 41 entries. In problems with large but sparse state spaces (game positions, strings with few reachable suffixes) that difference can be decisive.

Test yourself

How many calls does the memoized rod-cutting procedure make for n=10n = 10, counting the first one?

  1. 1111
  2. 5656
  3. 100100
  4. 10241024

In the subproblem graph of rod cutting for length nn, how many edges are there?

  1. nn
  2. n+1n + 1
  3. n(n+1)2\frac{n(n+1)}{2}
  4. 2n2^n

Why does r(5000) with functools.cache raise a RecursionError when r(150) works?

  1. The cache is too small
  2. The first call recurses about 5000 levels deep before anything is cached, beyond Python's recursion limit
  3. Memoization does not work for large nn
  4. The prices list is too short