Bottom-Up Tables
Memoization works from the top: ask the big question, and the recursion asks the smaller ones it needs. Dynamic programming (DP) can also run the other way, from the bottom: answer the smallest questions first, in a table, so every bigger answer finds what it needs already filled in.
The same idea, as a loop
Take the cheapest way to buy exactly x litres of paint. The last can in the basket is one of the sizes on sale, so:
best[x] = the lowest of best[x - size] + price for every can that fits
best[0] = 0 (nothing to buy)
best[x] only needs entries for smaller amounts. So fill the table from 0 upwards, and every entry you need is already there:
best := make([]int, n+1) // best[0] is 0
for x := 1; x <= n; x++ {
best[x] = -1 // not possible, until a can proves otherwise
for _, c := range cans {
// try c as the last can: best[x-c.Litres] + c.Price
}
}
No recursion, no map: a slice indexed by the amount, and a loop in the right order. For many puzzles this is the simplest DP to write once you know the formula.
Marking "not possible"
Some amounts can't be made at all: with only 2- and 5-litre cans there's no way to get exactly 3 litres. Mark those entries with a value that can't be a real answer, such as -1, and skip them when building bigger entries. Forgetting this check is the classic DP bug: -1 + price quietly turns "impossible" into a cheap-looking number.
Top-down or bottom-up?
| Memoised recursion | Bottom-up table | |
|---|---|---|
| Reads like | the problem | a formula |
| Works out | only the states it needs | every state up to n |
| Storage | a map | a slice (or a 2D slice) |
| Deep recursion | possible | never |
Both give the same answers. Start with whichever you can write correctly; switch when the other one is clearly simpler.
Task
This lesson's input says how much paint is needed, then lists the cans on sale: litres and price. There is at least one can, and every can holds at least 1 litre.
- Complete
costTable(cans []Can, upTo int) []int: entries0toupTo, where entryxis the lowest price for exactlyxlitres, or-1when no mix of cans makes exactlyx. - Complete
cheapest(cans []Can, litres int) (int, bool): the lowest price for exactlylitres, andfalsewhen it can't be done. - Complete
cheapestAtLeast(cans []Can, litres int) int: the lowest price for at leastlitres. Leftover paint is fine. Hint: buying more thanlitres + biggest - 1litres (withbiggestthe largest can) never helps, because one can could be left out.