Coin change with dollar amounts
- Say why 0.1 + 0.2 isn't 0.3 and why int(x * 100) turns 0.29 into 28 cents, then get exact whole cents with round
- Spot a dynamic program, where the best answer is built from best answers to smaller amounts and the same amounts come up again and again
- Fill the fewest-coins table and the number-of-ways table, and pick the loop order that counts combinations, not orderings
- Show why greedy fails for some coin sets, and check whether it's safe for yours
- Compare a recursive version with a cache against a table, and say what each one costs in Python
- Return the coins themselves, and handle unreachable amounts, a limited supply of each coin and very large amounts
Coin change with dollar amounts
In one Airbnb MLE (machine learning engineer) loop, reported in August 2026, the coding question was "a Coin Change variant, except the input wasn't integers, it was floats" (1 report). A prep site lists two more exact-sum questions for Airbnb MLE rounds (2 sources). Level 1 reads like this:
Amounts and coin values are dollars, as floats, like
0.25. Writemin_coins(amount, coins): the fewest coins that add up to exactlyamount, or-1if no mix of coins does. Each coin can be used any number of times.
Call Returns min_coins(0.30, [0.10, 0.25])3min_coins(0.65, [0.05, 0.10, 0.25])4min_coins(0.07, [0.05])-1Be ready to say why taking the biggest coin each time fails for some coin sets, and what your solution costs.
Thirty cents is three dimes. A quarter leaves 5 cents, and no coin fits. Level 2 adds count_ways(amount, coins): how many combinations make the amount, with order ignored, so 5 + 1 and 1 + 5 are one. Level 3 returns the coins of one best answer, and level 4 gives the till a limited supply of each coin.
You don't write it yet. The table that solves it may be familiar, but the floats are where working solutions break, so the lesson starts with whole cents and then builds the table. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
This is the first dynamic programming lesson. Its table is a list indexed by the amount, used the way the earlier lessons used a dict. The lesson on dynamic programming on a table grows the same idea into two dimensions.
Floats can't hold most amounts of money
The amounts in this problem are dollars, such as 0.29. Before any table, check how Python stores them.
0.1 + 0.2 is not 0.3
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
What do 0.1 + 0.2 and 0.1 + 0.2 == 0.3 print?
Decimal(0.1) prints the exact value Python stored for 0.1. Is it above or below 0.1?
A table needs whole numbers
A coin-change solution keeps a table with one cell for each amount. It asks whether some mix of coins hits the target exactly. Floats can't do either job.
seen = {0.1 + 0.2: "reached"}
print(0.3 in seen)
seen = {0.1 + 0.2: "reached"}. Is 0.3 a key?
What does table[0.30 * 100] do?
int cuts 0.29 down to 28 cents, round doesn't
The obvious conversion is int(x * 100). It's wrong. Here it is next to round(x * 100):
print("dollars x * 100 int round")
for x in [0.07, 0.30, 0.29, 0.57, 1.15]:
print(f"{x:<8.2f} {x * 100!r:<19} {int(x * 100):<4} {round(x * 100)}")
What does int(1.15 * 100) give?
Over the 100,000 amounts from $0.01 to $1,000.00, how many does int get wrong, and how many does round?
What do round(0.125 * 100) and round(13.5) give?
Decimal is exact only when you give it text
The decimal module can hold 0.29 exactly, but only if you hand it the digits as text:
print(Decimal(0.29))
print(int(Decimal(0.29) * 100))
print(int(Decimal("0.29") * 100))
What do int(Decimal(0.29) * 100) and int(Decimal("0.29") * 100) give?
Spot the dynamic program
The best way to make 6 cents is one coin plus a best way to make the rest
Say the coins are 1, 3 and 4 cents, and you want 6 cents. Some coin comes last. Try each one:
Tap 6: you don't know which coin comes last, so try them all and keep the smallest. Then tap the smaller amounts. As a formula:
is the fewest coins that make cents. The min tries every coin no bigger than . An amount that no coin leads to gets , which means unreachable.
This works because the rest has to be a best answer too. Say the best way to make 6 cents ends with a 3-cent coin. The other coins make 3 cents. If a better way to make 3 cents existed, you could swap it in and beat the best answer for 6, which can't happen. This is called optimal substructure: the best answer is built from best answers to smaller problems.
In the editor, best already holds the fewest coins for 0 to 5 cents, from coins of 1, 3 and 4. Write cell(t, values, best): from the formula, 1 plus the smallest best[t - v] over every coin v that fits, or math.inf if none fits.
Plain recursion asks the same question millions of times
The formula is correct. The question is what it costs.
Plain recursion makes 50 cents from coins of 1, 5, 10 and 25. About how many calls?
Fewest coins: fill a table from 0 up
Each cell looks back one coin
Fill the table from 0 up, so every is ready before needs it:
import math
def min_coins(amount: float, coins: list[float]) -> int:
"""The fewest coins that make amount exactly, or -1."""
target = round(amount * 100)
values = sorted({round(c * 100) for c in coins})
# best[t]: fewest coins for t cents
best = [0] + [math.inf] * target
for t in range(1, target + 1):
for v in values:
if v <= t and best[t - v] + 1 < best[t]:
best[t] = best[t - v] + 1
return -1 if best[target] == math.inf else best[target]
print(min_coins(0.06, [0.01, 0.03, 0.04]))
print(min_coins(1.15, [0.05]))
print(min_coins(0.03, [0.02, 0.05]))
What do the three calls give: 6 cents from 1, 3, 4, then $1.15 from nickels, then 3 cents from 2 and 5?
Greedy takes the biggest coin, and that can fail
Greedy never takes a coin back
The cashier's method takes the biggest coin that fits, then repeats. That's greedy. Here it is next to the table:
def greedy(amount: float, coins: list[float]) -> int:
"""Biggest coin first, never taken back. The coin count, or -1."""
left, used = round(amount * 100), 0
for v in sorted({round(c * 100) for c in coins}, reverse=True):
used += left // v
left %= v
return used if left == 0 else -1
for amount, coins in [(0.06, [0.01, 0.03, 0.04]),
(0.30, [0.10, 0.25]),
(0.30, [0.01, 0.10, 0.25])]:
print(greedy(amount, coins), min_coins(amount, coins))
Greedy against the table, for 6 cents from coins of 1, 3 and 4?
You can check whether greedy is safe for a coin set
Compare greedy with the table on every amount below the sum of the two largest coins:
def first_greedy_miss(coins: list[float]) -> int | None:
"""The smallest amount in cents where greedy loses to the table, or None."""
two_largest = sorted(coins)[-2:]
for cents in range(1, round(sum(two_largest) * 100)):
amount = cents / 100
if greedy(amount, coins) != min_coins(amount, coins):
return cents
return None
print(first_greedy_miss([0.01, 0.05, 0.10, 0.25]))
print(first_greedy_miss([0.01, 0.03, 0.04]))
Where does greedy first lose to the table: for US coins, and for 1, 3 and 4?
Why is it enough to check below the sum of the two largest coins?
Count the ways with the coin loop outside
Order ignored is a combination, order counted is an ordering
Here are all the ways to make 6 cents from coins of 1, 3 and 4:
| A combination, order ignored | Its orderings, order counted | How many |
|---|---|---|
| 1+1+1+1+1+1 | 1+1+1+1+1+1 | 1 |
| 3+1+1+1 | 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3 | 4 |
| 3+3 | 3+3 | 1 |
| 4+1+1 | 4+1+1, 1+4+1, 1+1+4 | 3 |
| 4 combinations | 9 orderings | 9 |
The problem asks for combinations. The order of your two loops decides which one you count. Here is the version with the coins outside:
def count_ways(amount: float, coins: list[float]) -> int:
"""Combinations that make amount exactly, order ignored."""
target = round(amount * 100)
values = sorted({round(c * 100) for c in coins})
# one way to make 0: no coins
ways = [1] + [0] * target
# coins outside
for v in values:
# amounts inside
for t in range(v, target + 1):
ways[t] += ways[t - v]
return ways[target]
print(count_ways(0.06, [0.01, 0.03, 0.04]))
4
ways[t] is the number of ways to make t cents. Each coin makes one pass over the amounts, from its own value up, and adds ways[t - v] to ways[t]. That counts the 4 combinations. Swap the two loops, with the amounts outside and every coin that fits inside, and the same addition counts the 9 orderings.
The table is the same shape as for the fewest coins. Only the rules change:
| Fewest coins | Number of ways | |
|---|---|---|
| a cell holds | the fewest coins that make | how many combinations make |
| start | best[0] = 0, every other cell | ways[0] = 1, every other cell 0 |
| combine | the min over coins, plus 1 | the sum over coins |
| loop order | either one | coins outside |
| unreachable | -1 | 0 |
ways[0] = 1 is not a hack. There is exactly one way to make 0 cents: take no coins. Every count is built on it, because a coin worth exactly adds ways[0] to ways[t]. Start it at 0 and every count stays 0. It's also why count_ways(0.0, [0.25]) is 1.
In the editor, write orderings(target, values), in cents: how many sequences of coins make target, with order counted. Put the amount loop outside, and the coins that fit inside it.
Coins outside: each pass lets in one more coin
Print the list after each coin's pass:
coins, ways = [1, 3, 4], [1] + [0] * 6
print(f"{'no coins':<17}{ways}")
for i, v in enumerate(coins):
for t in range(v, 7):
ways[t] += ways[t - v]
print(f"{'coins ' + str(coins[:i + 1]):<17}{ways}")
After the 3-cent pass, what is ways[6]?
Amounts outside: any coin can be last, so orderings count
Your orderings function put the loops the other way round. Here is the table it fills:
With the amount loop outside, any coin can be the last one at any amount:
counts the sequences that make , grouped by their last coin. So 1 + 1 + 4 and 1 + 4 + 1 end differently, and they count twice.
For the fewest coins, the loop order doesn't matter. A minimum doesn't care what order the coins arrived in, and both orders fill the same table. Only counting depends on it.
Some amounts can't be made
Every amount so far could be made from the coins. Change the coins, and some amounts can't.
With coins of 2 and 5, nothing makes 1 or 3 cents
amounts = range(11)
print("cents ", *[f"{t:>3}" for t in amounts])
print("fewest", *[f"{min_coins(t / 100, [0.02, 0.05]):>3}" for t in amounts])
print("ways ", *[f"{count_ways(t / 100, [0.02, 0.05]):>3}" for t in amounts])
Coins of 2 and 5 cents. Which amounts from 0 to 10 can't be made?
Coins of 10 and 25. Their GCD, the largest number that divides both, is 5. Can any mix make 32 cents?
What does reduce(math.gcd, [12, 18, 8]) give?
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 for the amount in cents and for the number of distinct coins. Both functions visit amounts and try coins at each:
The unit is part of the answer.
Space is one row of cells. The counting table drawn with one row per coin would be cells, and the flat list keeps a single row. Rebuilding the coins adds one more row of .
One more digit makes the table ten times longer
A table in cents for $1,000,000. How many cells?
Top-down is the same formula, as a recursive function with a cache
Everything so far is bottom-up: a list filled from 0 to the target. The other way is top-down: the formula as a recursive function, with a cache so each amount is solved once.
import math
from functools import cache
def min_coins_top_down(amount: float, coins: list[float]) -> int:
"""min_coins as a recursive function with a cache."""
values = sorted({round(c * 100) for c in coins}, reverse=True)
@cache
def best(t: int) -> float:
"""The fewest coins for t cents, or math.inf."""
if t == 0:
return 0
return min((best(t - v) + 1 for v in values if v <= t),
default=math.inf)
answer = best(round(amount * 100))
return -1 if answer == math.inf else answer
print(min_coins_top_down(0.06, [0.01, 0.03, 0.04]))
print(min_coins_top_down(500.00, [0.01, 0.05, 0.10, 0.25, 1.00, 5.00]))
2
100
Both versions keep the same answers. They keep them in different places:
| For 6 cents from 1, 3 and 4 | What it holds |
|---|---|
| bottom-up: a list, filled from 0 up | [0, 1, 2, 1, 1, 2, 2] at indexes 0 to 6 |
| top-down: a dict inside the cache, filled as each call comes back | {0: 0, 1: 1, 2: 2, 3: 1, 4: 1, 5: 2, 6: 2} |
Read the min call inside out:
- For each coin
vthat fits,best(t - v) + 1is the fewest coins fortwithvas the last coin. - The inner parentheses make a generator of those counts, and
mintakes the smallest. default=math.infis whatminreturns when no coin fits, so an unreachable amount comes back asmath.inf.
@cache is just the shortest way to get that dict. A plain dict you fill yourself does the same job.
It's the formula almost word for word. That makes it the quickest way to get a correct answer on the board.
@cache hides the dict it keeps. In the editor, write best(t) inside fewest_memo(target, values) with the dict itself: look an amount up in memo before you work it out, and store it after. It prints the same three answers as the table.
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.
Top-down only visits amounts it can reach
Top-down has one real advantage over the table.
Coins of 5, 10 and 25, and $100. The table fills 10,001 cells. How many amounts does top-down visit?
A worked example: 30 cents from dimes and quarters
The practice problem's first test asks for min_coins(0.30, [0.10, 0.25]). Here is the whole path, with what to say at each step.
1. Name the trap. These are floats, so convert to cents with round, once. That gives 30 cents and coins of 10 and 25. Their GCD is 5, and 5 divides 30, so an answer may exist.
2. Fill the table. One cell per cent, from 0 to 30:
target = round(0.30 * 100)
values = [round(c * 100) for c in [0.10, 0.25]]
best = [0] + [math.inf] * target
for t in range(1, target + 1):
for v in values:
if v <= t and best[t - v] + 1 < best[t]:
best[t] = best[t - v] + 1
print(target, values)
print({t: best[t] for t in range(target + 1) if best[t] != math.inf})
Coins of 10 and 25. Which amounts up to 30 cents can be made?
The third line asks for an amount of 0 from quarters. How many coins, and how many ways?
What interviewers ask next
Levels 3 and 4 of the practice problem are the first two follow-ups here, and the third is very large amounts. Each one reuses the table.
Return the coins: keep the coin that set each cell
def coins_used(amount: float, coins: list[float]) -> list[float] | None:
"""The coins themselves, or None if no mix makes the amount."""
by_cents = {round(c * 100): c for c in coins}
target, values = round(amount * 100), sorted(by_cents)
best = [0] + [math.inf] * target
# the coin that set best[t]
last = [0] * (target + 1)
for t in range(1, target + 1):
for v in values:
if v <= t and best[t - v] + 1 < best[t]:
best[t], last[t] = best[t - v] + 1, v
if best[target] == math.inf:
return None
used, t = [], target
while t:
used.append(by_cents[last[t]])
t -= last[t]
return used
print(coins_used(0.06, [0.01, 0.03, 0.04]))
What does coins_used(0.06, [0.01, 0.03, 0.04]) return?
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]))
One quarter, five dimes and one nickel. The fewest coins for 60 cents?
One dime, and the loop runs upward over the amounts. How many dimes can 30 cents use?
13 dimes become bundles of 1, 2, 4 and 6 dimes. Can every count from 0 to 13 be made from the bundles?
Very large amounts: shrink the unit by the GCD
At $10,000,000 the table has a billion cells. There are three answers, and they stack: shrink the unit, check whether greedy is safe, and bound the table by the largest coin. Start with the cheapest.
Shrink the unit. Divide the amount and every coin by the coins' GCD, and fill the table in that unit. An amount the GCD doesn't divide is -1 at once.
Coins of 5, 10 and 25 cents. Counting in their GCD makes the table how much shorter?
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 , with no table at all.
Bound the table by the largest coin. Call the largest coin and the second largest . A best answer never holds of the smaller coins. Line up any of them and keep a running total: either one total is a multiple of , or two totals leave the same remainder and the coins between them add up to a multiple of . Each of those coins is smaller than , so fewer coins of can replace them.
So the smaller coins in a best answer add up to at most . Split the amount into from the smaller coins and coins of :
runs over the amounts from 0 to that leave a multiple of . The table only has to reach , whatever the amount. For the practice test's coins, is 500 cents and 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.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.
More exact-sum problems to practice
A prep site's question bank lists two more exact-sum DPs for Airbnb MLE rounds:
- the fewest items from an unlimited supply that add up to an exact target, listed for a technical screen (1 source)
- the fewest bookings that fill a layover exactly, listed for an onsite (1 source).
Both are min_coins under new names:
| Their words | Coin change words |
|---|---|
| item sizes, booking lengths | the coins |
| the target, the layover | the amount |
| fewest items, fewest bookings | min_coins |
Practice them by restating them that way out loud. Then ask the three questions this problem raises: are the values whole units, can the target be unreachable, and can each option be used more than once?
1.What does
int(0.29 * 100)return?2.Coins of 10 and 25 cents, amount 30 cents. What does greedy return?
3.You write
count_wayswith the amount loop outside and the coin loop inside. What does it return for 10 cents from coins of 1, 5 and 10?4.The amount is 500 dollars and there are 6 coin values. About how many inner-loop steps does the bottom-up
min_coinstake?5.You memoize the recursion with
functools.cacheand try the 1-cent coin first. What happens on the 500-dollar test with Python's default settings?
Where this shows up
The reports behind this lesson, each with its source.
Coding in the same loop: a coin change variant with float denominations.
A prep site lists another coin-change-style DP for an Airbnb MLE technical screen: fewest items summing exactly to a target.
And an MLE onsite DP on exact-duration sums: fewest bookings to fill a layover exactly.
Practice
Sources (7)
- Floating-Point Arithmetic: Issues and Limitations · Python 3.12 documentation · Oct 26, 2026
“Unfortunately, most decimal fractions cannot be represented exactly as binary fractions.”
- Built-in Functions: int · Python 3.12 documentation · Oct 26, 2026
“For floating-point numbers, this truncates towards zero.”
- Built-in Functions: round · Python 3.12 documentation · Oct 26, 2026
“If ndigits is omitted or is None, it returns the nearest integer to its input.”
- decimal: Decimal fixed-point and floating-point arithmetic · Python 3.12 documentation · Oct 26, 2026
“If value is a float, the binary floating-point value is losslessly converted to its exact decimal equivalent.”
- functools.cache · Python 3.12 documentation · Oct 26, 2026
“Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments.”
- sys.setrecursionlimit · Python 3.12 documentation · Oct 26, 2026
“This should be done with care, because a too-high limit can lead to a crash.”
- Optimal Bounds for the Change-Making Problem · DAIMI Report Series PB-371 · Nov 1, 1991
“In this paper we show that if a counterexample exists, then the smallest one lies in the range c_3 + 1 < x < c_m + c_m-1, and these bounds are tight.”