24/28
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.
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?

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?

Pick an answer above to see the rest