CodeArchon

medium1-D Dynamic ProgrammingAmazonFacebook

Minimal Coin Changer

A cashier returns a specific amount using the fewest coins from an unlimited supply of given denominations.

Given coins of distinct denominations and a target amount, return the fewest coins needed to make up that amount or -1 if impossible.

Choose approach

0
0
?
1
?
2
?
3
?
4
?
5
?
6
?
7
?
8
?
9
?
10
?
11
i
1/13
Narrationstep 1 of 13

Base dp[0] = 0.

1def coinChange(coins, amount):
2 dp = [float('inf')] * (amount + 1); dp[0] = 0
3 for a in range(1, amount + 1):
4 for c in coins:
5 if a - c >= 0: dp[a] = min(dp[a], dp[a - c] + 1)
6 return -1 if dp[amount] == float('inf') else dp[amount]
Variables
amount=11
coins=1,2,5

How to think about it

  1. Order of iteration (a outer, coins inner) correctly allows coin reuse.
  2. No valid combination -> dp[amount] stays infinity.

Edge cases to catch in interview

  • amount=0 -> 0.
  • No coin ≤ amount -> -1.

Examples

Example 1-1
{"coins":[2],"amount":3}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed