Greedy and dynamic programming

When taking the best step works, when it does not, and memoisation as the fix.

8 min read🧮 Data Structures and Algorithms in Java

Two ways to build an answer out of smaller answers. Greedy takes the best step available and never reconsiders; dynamic programming considers everything but refuses to solve the same thing twice.

Knowing which applies is most of the work, and there is a test for it.

Greedy, and the question that decides whether it is allowed

Making change for 30 from coins of 25, 10 and 5, always taking the largest that fits: 25, then 5. Two coins, and it is optimal.

Now coins of 25, 10 and 1, making 30. Greedy takes 25, then five 1s — six coins. The right answer is three 10s.

Same algorithm, same shape of problem, and it is wrong on the second. So greedy is not a technique you apply; it is a property a problem either has or does not:

Does taking the locally best step always leave a situation from which the overall best answer is still reachable?

For the first coin set, yes. For the second, no — taking 25 destroys the 10-10-10 answer. Nothing in the code tells you which you have, which is why greedy solutions need an argument, not just a test.

Where greedy provably works, it is the cheapest thing available: interval scheduling by earliest finish time, Huffman coding, Dijkstra's next-cheapest-vertex, Kruskal's cheapest-edge-that-does-not-cycle.

When greedy fails, the answer is usually "try everything, but remember"

java
static long fib(int n) { return n < 2 ? n : fib(n-1) + fib(n-2); }

Correct, elegant, and it re-solves the same subproblems an exponential number of times. fib(40) computes fib(38) twice, fib(37) three times, fib(36) five times — the counts are themselves Fibonacci numbers.

plaintext
### naive fib(40)     = 102334155  (285 ms)
### memoised fib(90)  = 2880067194370816120  (0 ms)

Read those two lines together. The naive version took 285 milliseconds for 40. The memoised version did 90 in unmeasurable time — and 90 is not twice as hard as 40, it is astronomically harder. Naive fib(90) would not finish in your lifetime.

The change is four lines:

java
static long fib(int n, long[] memo) {
    if (n < 2) return n;
    if (memo[n] != 0) return memo[n];
    return memo[n] = fib(n-1, memo) + fib(n-2, memo);
}

That is dynamic programming. Not a technique with its own theory — recursion, plus not doing the same work twice.

The two conditions

A problem is a DP when both hold:

  1. Optimal substructure — the best answer is built from best answers to smaller versions. (Greedy needs this too.)
  2. Overlapping subproblems — those smaller versions repeat. (Greedy problems do not have this; that is why greedy can throw away what it has seen.)

If only the first holds, it is divide and conquer — merge sort, binary search — and there is nothing to memoise because nothing repeats.

Top-down or bottom-up

Memoisation is top-down: write the recursion, add a cache. Natural to write from the problem statement, and it only computes states you actually need. Its cost is the call stack — and the recursion lesson's ceiling of about forty-five thousand frames is real here.

Tabulation is bottom-up: fill a table from the smallest case upward.

java
long[] dp = new long[n+1];
dp[1] = 1;
for (int i = 2; i <= n; i++) dp[i] = dp[i-1] + dp[i-2];

No recursion, no stack limit, and often less memory — because you can frequently discard everything except the last row or two:

java
long a = 0, b = 1;
for (int i = 2; i <= n; i++) { long c = a + b; a = b; b = c; }

O(n) time, O(1) space. Recognising that the table only ever reads a fixed window back is the standard second optimisation, and on a large DP it is the difference between fitting in memory and not.

Recognising a DP

The signals, in rough order of reliability:

  • The question asks for a minimum, maximum, or count of ways.
  • You can describe the answer for n in terms of the answer for smaller n.
  • The obvious recursion is exponential, and you can see the same arguments recurring.
  • Choices at each step, where an earlier choice constrains later ones.

The standard shapes worth recognising rather than deriving: coin change, knapsack, longest common subsequence, edit distance, longest increasing subsequence, paths through a grid.

Under the hood: what memoisation costs beyond the Big-O

"Memoised" is not free just because it is polynomial — the cache itself has a mechanism, and which one you pick matters at scale.

A HashMap<Integer, Long> cache, the version people reach for first, pays for every lookup: box the int key to an Integer, compute its hash, walk the bucket (a linked list, or a red-black tree once a bucket treeifies), then unbox the result on the way out. An long[] array memo, the version this lesson actually uses, skips all of it — the key is the index, so a lookup is one bounds-checked array read, no hashing, no boxing, and — because a Java array is one contiguous block — far better cache locality than objects scattered across the heap by a hash table's internal nodes. For a DP over a small, dense range of integers (which describes most textbook DP states — an index, a remaining capacity, a position in two strings), the array is not a micro-optimisation, it is removing an entire unnecessary layer.

Tabulation's cache advantage runs deeper than "no recursion overhead". Filling dp[i] from dp[i-1] in a loop touches memory sequentially, which is exactly the access pattern a CPU's hardware prefetcher is built to anticipate — by the time the loop reads dp[i-1], it is very likely already sitting in L1 cache from prefetching the line that held dp[i-2] and dp[i-1] together. A top-down memoised call tree, by contrast, jumps around the call stack and the heap in an order driven by the recursion, not by memory layout — and every call is also a stack frame, with its own push/pop cost on top of the actual work. This is why the lesson's O(1)-space rolling variables (long a = 0, b = 1; …) are doubly fast: they turn an already cache-friendly sequential scan into a constant working set that fits in a register or an L1 line for the whole computation, rather than a table that grows with n.

Try it yourself

Count the actual work a memoised call tree does

Before running anything: a memoised fib(n) computes each distinct subproblem exactly once. For fib(10), how many new computations happen — not counting the calls that hit the cache or the two base cases fib(0) and fib(1)?

java
class Fib {
    static long[] memo = new long[50];
    static int computed = 0;
    static long f(int n) {
        if (n < 2) return n;
        if (memo[n] != 0) return memo[n];
        computed++;
        return memo[n] = f(n - 1) + f(n - 2);
    }
}
System.out.println("fib(10) = " + Fib.f(10) + ", computed " + Fib.computed + " new subproblems");
Why the count is n − 1, not exponential

There is exactly one distinct subproblem for each value of n from 2 up to 10 — nine of them — and the cache guarantees each is computed once no matter how many times it is asked for. The naive version's 285 ms at fib(40) comes entirely from asking for the same nine-ish values (scaled up to 40) an exponential number of times; memoisation does not change what is computed, it changes how many times the same answer gets recomputed from scratch.

Misconceptions

  • "Memoisation and tabulation always have the same complexity, so it does not matter which you pick." They have the same asymptotic time, but memoisation adds a per-call cache lookup and a stack frame that tabulation's sequential array walk does not — and tabulation's rolling-array reduction to O(1) space is usually not reachable from a naive top-down cache, because the recursion still needs the full table to know what it has already asked for.
  • "A HashMap cache is the natural choice for memoisation." It is the natural choice when the state is not a small dense integer (a pair of strings, say, keyed by a combined hash) — but when the state is a small integer range, an array both avoids boxing and gives far better cache locality, for the same asymptotic complexity.

Sources

  • Thomas H. Cormen et al., Introduction to Algorithms (CLRS) — dynamic programming, optimal substructure and overlapping subproblems.
  • OpenJDK java.util.HashMap source — bucket structure, treeification, and the cost a lookup pays versus a plain array index.
  • Jon Bentley, Programming Pearls — on the practical difference between an algorithm's asymptotic cost and what its constants actually do to real hardware.
Progress is saved on this device and to your account when signed in.