Dynamic programming · Problem 2 of 3

Fewest coins to make change

Pattern: Coin Change: Fewest Coins with DP

mediumNot solved yet

The problem

A vending machine has unlimited coins of each value in coins (all positive, no duplicates). Write a function that returns the fewest coins that add up to exactly amount, or -1 if it can't be done. An amount of 0 needs 0 coins.

text
1fewest_coins([1, 3, 4], 6)  ->  2
2fewest_coins([5, 10], 3)    ->  -1
3fewest_coins([2], 0)        ->  0

In the first example, 3 + 3 uses two coins. Taking the biggest coin first (4 + 1 + 1) uses three.

Write fewest_coins(coins, amount) in Python or fewestCoins(coins, amount) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 22 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.