Yasir Explains/Algorithms/Dynamic Programming/Coin Change
Dynamic Programming

Coin Change

On this page

ProblemDP recurrence relationDP memoizationDP base caseCounting combinations (optional)PseudocodeComplexity
Dynamic Programming

Coin Change

Fewest coins to make an amount: try one coin, recurse on what is left, remember answers per amount.

Problem

You have several coin values (positive integers). You may use as many of each coin as you want. Given a target amount A, find the smallest number of coins whose values add up to A. If it cannot be done, say so (in the code below, the caller checks the answer against a special “too big” value).

Example: coins {1, 3, 4}, A = 6. One option is 4 + 1 + 1 (three coins); another is 3 + 3 (two coins). The answer is 2.

DP recurrence relation

Let dp(x) = minimum number of coins to make amount x.

Think one step at a time. Suppose the last coin you use has value c. Then the other coins must make x − c, which needs dp(x − c) coins. So this choice uses dp(x − c) + 1 coins in total.

You do not know which c is best, so try every coin that does not overshoot (c ≤ x) and pick the smallest result:

Example
dp(x) = minimum of ( dp(x - c) + 1 )
over every coin c with c <= x

Small example: dp(6) with coins 1, 3, 4:

  • use 1 last → dp(5) + 1
  • use 3 last → dp(3) + 1
  • use 4 last → dp(2) + 1

Take the minimum of those three numbers (after you know dp for the smaller amounts).

DP memoization

Store memo[0] … memo[A]. If memo[x] is already filled, return it instead of recomputing.

Only amounts 0 … A appear, so there are A + 1 states. Each state tries each coin once → O(A × number of coins) time and O(A) space.

DP base case

Example
dp(0) = 0

Explanation: Amount zero needs no coins.

If no coin fits x, or every recursive branch is “impossible,” then dp(x) has no solution. In code we use a large integer INF for “impossible” so we can still take min safely.

Counting combinations (optional)

Counting how many ways to make A (order does not matter) uses a two-parameter DP g(i, x) — different problem. This page only covers minimum coin count.

Pseudocode

Recursive DP with memo:

1MIN-COINS(x, coins, memo, INF)
2 if x == 0
3 return 0
4 if memo[x] is ready
5 return memo[x]
6 ans = INF
7 for each coin c
8 if c <= x
9 t = MIN-COINS(x - c, coins, memo, INF)
10 if t < INF
11 ans = min(ans, t + 1)
12 memo[x] = ans
13 return ans

Complexity

Time: O(A · |coins|). Space: O(A).

Complexity Analysis

Time Complexity

O(A · |coins|)

Space Complexity

O(A)

Pseudo-polynomial in the numeric amount A

Growth Rate Comparison

n (input size)O(1)O(log n)O(n)O(n log n)O(n²)