26/28
Part 7 of 7 · What interviewers ask nextLearn

Very large amounts: try greedy, then bound the table

Check whether greedy is safe. If the coin set passes the canonical check from the greedy section, greedy answers any amount in O(n)O(n), with no table at all.

Bound the table by the largest coin. Call the largest coin LL and the second largest SS. A best answer never holds LL of the smaller coins. Line up any LL of them and keep a running total: either one total is a multiple of LL, or two totals leave the same remainder and the coins between them add up to a multiple of LL. Each of those coins is smaller than LL, so fewer coins of LL can replace them.

So the smaller coins in a best answer add up to at most (L−1) S(L - 1)\,S. Split the amount AA into rr from the smaller coins and (A−r)/L(A - r) / L coins of LL:

F(A)=min⁡r(F(r)+A−rL)F(A) = \min_{r} \left( F(r) + \frac{A - r}{L} \right)

rr runs over the amounts from 0 to (L−1) S(L - 1)\,S that leave A−rA - r a multiple of LL. The table only has to reach (L−1) S(L - 1)\,S, whatever the amount. For the practice test's coins, LL is 500 cents and SS is 100, so that's 49,900 cents: 49,901 cells for any amount.

Watch the count's size. Python's integers don't overflow. But with the practice test's six coins, the number of ways to make $10,000 is a 67-bit number, past what a signed 64-bit integer holds. In another language, ask whether they want the count modulo a large prime.