Coding Interview PatternsCoin Change
MediumDynamic Programming
Coin Change
Explanation & Solution
Description
You are given an integer array coins representing coin denominations and an integer amount representing a total amount of money.
Return the fewest number of coins needed to make up that amount. If that amount cannot be made up by any combination of the coins, return -1.
You may assume you have an infinite supply of each kind of coin.
Input:coins = [1,5,10], amount = 12
0
1
1
5
2
10
Output: 3
Explanation: 12 = 10 + 1 + 1, which uses 3 coins.
Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4
Approach
Dynamic Programming pattern
1. Define the Subproblem
- Let
dp[i]be the minimum number of coins needed to make amounti - We want to find
dp[amount]
2. Establish the Base Case
dp[0] = 0— zero coins are needed to make amount 0- Initialize all other entries to
Infinity(meaning "not yet achievable")
3. Write the Recurrence
- For each amount
ifrom1toamount: - For each coin denomination
cincoins: - If
c <= ianddp[i - c] + 1 < dp[i], thendp[i] = dp[i - c] + 1 - This means: if we use one coin of value
c, the remaining amounti - crequiresdp[i - c]coins
4. Build the Table Bottom-Up
- Process amounts from
1toamountin order - Each amount considers all coin denominations and takes the minimum
- After the loop,
dp[amount]contains the answer
5. Handle the Impossible Case
- If
dp[amount]is stillInfinity, no combination of coins can form the target amount - Return
-1in that case; otherwise returndp[amount]
Key Insight
- This is an unbounded knapsack variant solved with bottom-up DP
- Each amount builds on previously solved smaller amounts
Time
O(amount * coins.length)nested loop over amounts and coinsSpace
O(amount)one-dimensional DP arrayVisualization
Input:
Dynamic Programmingcoins = [1,5,10], amount = 12
dp
Press play to start DP animation
ComputingDependencyFilledEmpty
14 steps