19/28
Part 5 of 7 · What it costsLearn
In Python, top-down is slower and bigger, and it can run out of stack
It costs more than the table in three ways. The first two:
- Speed. Every amount is a function call through the cache, a thin wrapper around a dict lookup. On the practice problem's $500 test it takes about three times as long as the loop.
- Memory. A dict entry costs several times a list slot: about 2.6 MB for 50,001 amounts, against 0.4 MB for the list.
The third is the stack. The recursion goes as deep as the longest chain of calls that wait on each other:
With the coins tried smallest first, each call waits on the amount 1 cent less: best(500) waits on best(499), and so on down to best(0). That's about 500 calls waiting at once, 2 frames each: about 1,000 frames, Python's default limit.
- Python stops at 1,000 frames by default.
- With the largest coin tried first, as above, the $500 test peaks at 113 calls deep and passes.
- Sort the coins the other way and the chain walks down a cent at a time. On Python 3.12 it dies with
RecursionError: maximum recursion depth exceededby 500 cents. - Each level costs two frames: the function, and the generator inside
min. - With pennies alone, any order needs one level per cent.
Raising the limit is a gamble. The Python docs warn that a limit set too high can crash Python. On Python 3.12 the smallest-first version still fails at 1,666 cents with the limit set to 100,000.