Coin Change

35 min · coinChange()

A checkout total doesn't care which coin you reach for first. It cares how few coins you can get away with using.

You're given a list coins, where each value is a denomination — the amount one kind of coin is worth — and a non-negative integer amount. You have an unlimited supply of every denomination. Return the fewest coins needed to total exactly amount.

A few ground rules:

  • Return -1 when no collection of the available coins reaches the amount.
  • Return 0 when amount is 0; choosing no coins already makes that total.
  • You may use the same denomination as many times as needed.

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 1_000
  • 0 <= amount <= 10_000

Hints

Search totals, not coin lists

Start at total 0. Adding one coin takes you to another reachable total. The first time a level-by-level search reaches amount, it has used the fewest coins.

Ask one smaller question

To make total a with a final coin coin, you first need the best answer for a - coin. Try every denomination that fits.

Mark the impossible

Fill an array with a value larger than any possible answer, set dp[0] = 0, and update dp[a] = min(dp[a], dp[a - coin] + 1). An untouched final entry means -1.

Follow-up

How would you return one actual minimum-length collection of coins, not just its size?

Visible cases

Examples

Example 1

ready
Input
coins = [
  1,
  2,
  5
]
amount = 11
Expected
3
Why
5 + 5 + 1 reaches 11 with three coins

Example 2

ready
Input
coins = [
  2
]
amount = 3
Expected
-1
Why
repeating 2 can never make the odd total 3

Example 3

ready
Input
coins = [
  1
]
amount = 0
Expected
0
Why
the empty selection makes amount 0

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite