100 XP

90. Fewest coins

Advanced dynamic programming

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

Inputcoins = [1, 3, 4], amount = 6
Output2
Explanation3 + 3. The biggest-first way needs 3 coins.

Example 2

Inputcoins = [2], amount = 3
Output-1
Explanation2s can only make even amounts.

Example 3

Inputcoins = [1, 5, 10], amount = 0
Output0
ExplanationNothing to pay: no coins.

Constraints

  • coins has 1 to 10 different whole numbers, each from 1 to 1000.
  • amount is a whole number from 0 to 5000.

Submit also runs 9 more tests you can't see.

Code
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