Exact Change Machine

Medium · 1-D Dynamic Programming · about 20 min

A ticket machine must hand back exactly amount cents using coins whose values are in coins. It has an unlimited supply of each coin. Return the fewest coins that add up to exactly amount, or -1 if no mix of coins can make it.

  • 1 <= len(coins) <= 12, each coin is between 1 and 10,000 and they are all different.
  • 0 <= amount <= 10000. Making 0 needs 0 coins.

Examples:

fewest_coins([1, 3, 4], 6) → 2 (3 + 3)

fewest_coins([2], 3) → -1

Hints

  • Think about the last coin the machine hands out. What amount was left before it?
  • Build the answer for every amount from 0 up to the target. Amount 0 needs no coins.
  • Keep a value that means 'cannot be made' and turn it into -1 only at the very end.

Learn the pattern first: the 1-D Dynamic Programming lesson.

More 1-D Dynamic Programming problems