Coin Change
MediumNeetCode 150Top Interview 150 1-D Dynamic ProgrammingDatadogGeicoMastercardPinterestProblem
You have coins of several values and an unlimited supply of each. Given a target
amount, return the fewest coins that add up to exactly that amount.
If no combination of coins can make the amount, return -1.
Constraints
- 1 ≤ coins.length ≤ 12
- 1 ≤ coins[i] ≤ 100
- 0 ≤ amount ≤ 20
Examples: pick one to animate
Solutions
TimeO(amount × coins)
SpaceO(amount)
Time: Each amount from 1 to the target tries every coin once.
Space: The dp array holds amount + 1 values.
dp[a] is the fewest coins that make a. For each amount, try every coin
c that fits and take dp[a - c] + 1. An unreachable amount keeps a value
bigger than the target, which tells us to return -1.