loading

Coin Change — Step-by-Step Visualization

mediumLeetCode #322ArrayDynamic ProgrammingBreadth-First Search

You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return `-1`.

Algorithm Pattern

Dynamic Programming (Bottom-up)

Key Idea

We build a DP table `dp[i]` which represents the minimum number of coins to make up amount `i`. For each amount `i` from 1 to `amount`, we try each coin in `coins`. If we use a coin `c`, the number of coins is `1 + dp[i - c]`. We take the minimum of these values.

Step-by-Step Approach

  1. Initialize a `dp` array of size `amount + 1` filled with `amount + 1` (a value larger than any possible answer).
  2. Set `dp[0] = 0` (base case: 0 coins for 0 amount).
  3. Iterate `i` from 1 to `amount`.
  4. For each coin `c` in `coins`:
  5. If `i - c >= 0`:
  6. `dp[i] = min(dp[i], 1 + dp[i - c])`.
  7. If `dp[amount]` is still `amount + 1`, return -1. Else return `dp[amount]`.

Common Gotchas

  • Infinite coin supply means we use the same `dp` entry for the same amount but different coins.
  • Ensure you handle the 'unreachable' case (return -1).

Related Problems