17/28
Part 5 of 7 · What it costsLearn and do

What it costs

Time is amount times coins, with the amount in cents

The practice problem's $500 test is 50,000 cents. With six coins, min_coins takes 300,000 inner steps: 6 coins at each of 50,000 amounts. count_ways takes 299,365, because each coin's pass starts at its own value. That runs in a few hundredths of a second, well under the test's 2-second limit.

In general, write AA for the amount in cents and nn for the number of distinct coins. Both functions visit A+1A + 1 amounts and try nn coins at each:

time=O(A⋅n),space=O(A)\text{time} = O(A \cdot n), \qquad \text{space} = O(A)

The unit is part of the answer.

Space is one row of A+1A + 1 cells. The counting table drawn with one row per coin would be (n+1)(A+1)(n + 1)(A + 1) cells, and the flat list keeps a single row. Rebuilding the coins adds one more row of A+1A + 1.

One more digit makes the table ten times longer

Predict

A table in cents for $1,000,000. How many cells?

Pick an answer above to see the rest