DPDynamic Programming

Coin Change (min coins)

Find the fewest coins that sum to an amount (or count the ways) using unlimited coins of given denominations.

Learn Coin Change →
1
0
3
1
4
2
0123456
0
1/20dp[a] = fewest coins that sum to a. Amount 0 needs 0 coins; everything else starts at ∞ (unknown / impossible).
Cell being filledDependency readBase caseComputedReconstructed choice
1dp[0] = 0; dp[1..A] = ∞
2for a in 1 .. A:
3 for coin in coins:
4 if coin <= a and dp[a-coin] + 1 < dp[a]:
5 dp[a] = dp[a-coin] + 1; from[a] = coin
6return dp[A] (∞ means impossible)
Variables
A6
Complexity
best O(amount · k)
avg O(amount · k)
worst O(amount · k)
space O(amount)
Speed