90. Fewest coins
Write a function fewest_coins(coins, amount) that takes a list of coin values and an amount, and returns the fewest
coins that add up to exactly that amount. There are as many coins of each value as you need.
- If no mix of coins makes the amount exactly, return -1.
- An amount of 0 takes 0 coins.
Taking the biggest coin that fits, again and again, works for everyday money but not for every set of coins: with coins 1, 3 and 4, it makes 6 as 4 + 1 + 1 (three coins), while 3 + 3 takes two. Instead, work out the best answer for every smaller amount first.
Example 1
coins = [1, 3, 4], amount = 62Example 2
coins = [2], amount = 3-1Example 3
coins = [1, 5, 10], amount = 00Constraints
coinshas 1 to 10 different whole numbers, each from 1 to 1000.amountis a whole number from 0 to 5000.
Submit also runs 9 more tests you can't see.
- Make a list
bestwith one place for every amount from 0 toamount:best[a]will be the fewest coins that makea.best[0]is 0; start the rest at infinity,float("inf"), meaning "can't be made yet". - Work through the amounts from 1 up. For each coin
cthat fits, using it last meansbest[a - c] + 1coins: keep the smallest of those. best[amount]is the answer, unless it is still infinity: then return -1.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def fewest_coins(coins, amount):
"""Find the fewest coins that make amount exactly.
coins: list of int, the coin values (unlimited each)
amount: int, 0 or more
Returns: int, the fewest coins, or -1 if the amount
can't be made
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.