Part 7 of 7 · What interviewers ask nextLearn and do
A limited supply: run the amount loop downward
Now the till holds 1 quarter, 5 dimes and 1 nickel. For the fewest coins, treat every physical coin as an item you can use once, and run the amount loop downward:
def min_coins_limited(target: int, supply: list[tuple[int, int]]) -> int: """The fewest coins for target cents, with supply as (cents, count) pairs.""" best = [0] + [math.inf] * target for v, k in supply: # each coin once for _ in range(k): # downward for t in range(target, v - 1, -1): best[t] = min(best[t], best[t - v] + 1) return -1 if best[target] == math.inf else best[target]print(min_coins_limited(60, [(25, 1), (10, 5), (5, 1)]))print(min_coins(0.60, [0.25, 0.10, 0.05]))
Predict
One quarter, five dimes and one nickel. The fewest coins for 60 cents?
Pick one to see what it prints.
With the limited till, 60 cents takes 5 coins: 25 + 10 + 10 + 10 + 5. With an unlimited supply it takes 3: 25 + 25 + 10. The direction of the loop is what keeps each coin to one use. Here is one dime, both ways:
Pick an answer above to see the rest
Predict
One dime, and the loop runs upward over the amounts. How many dimes can 30 cents use?
One dime, best starts as [0, ∞, ∞, ...]
Step
Gives
upward
t = 10: best[0] + 1
1
upward
t = 20: best[10] + 1
2: the same dime again
upward
t = 30: best[20] + 1
3: and again
downward
t = 30: best[20] + 1
∞: 20 isn't set yet
downward
t = 20: best[10] + 1
∞: 10 isn't set yet
downward
t = 10: best[0] + 1
1: the dime, used once
Going down, best[t - v] still holds its value from before this coin arrived, so the coin is used at most once. Going up, the coin can build on itself, which is the unlimited version.
That's O(A⋅K) for K coins in the till. To cut it, split each stack of k copies into bundles of 1, 2, 4 and so on, plus whatever is left:
Pick an answer above to see the rest
Predict
13 dimes become bundles of 1, 2, 4 and 6 dimes. Can every count from 0 to 13 be made from the bundles?
Treat each bundle as one item that adds its number of coins to the count. The work drops to O(A∑logk): the sum, over the coin values, of the log of each stack's size.
Counting with a limited supply needs a different fix. Don't split into copies:
Two dimes as two items
How many dimes to take
10 = dime A, and 10 = dime B
10 = one dime
2 ways counted, 1 combination
1 way
Loop over how many of each coin you take instead:
Wi(t)=j=0∑kiWi−1(t−jci)
j is how many copies of coin ci you take, from 0 up to its supply ki. A running sum over that window brings it back to O(A⋅n).
In the editor, write the loop in can_make_once(target, values): whether some of the coins, each used at most once, add up to target. ok[t] says whether t cents can be made so far. Run the amount loop downward.
Pick an answer above to see the rest
Instructions
1
Write can_make_once(target, values): whether some coins, each used at most once, add up to target.