The Problem

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.

You may assume that you have an infinite number of each kind of coin.

Interactive Visualization

Speed:
DP Table (dp[i] = min coins to make amount i)
Current amount: โ€”
Trying coin: โ€”
Available Coins
Current Calculation
Press Step or Play to begin.
Status
Press Step or Play to begin.
Code
fun coinChange(coins: IntArray, amount: Int): Int {    val dp = IntArray(amount + 1) { Int.MAX_VALUE }    dp[0] = 0  // base case    for (i in 1..amount) {        for (coin in coins) {            if (coin <= i && dp[i - coin] != Int.MAX_VALUE) {                dp[i] = minOf(dp[i], dp[i - coin] + 1)    return if (dp[amount] == Int.MAX_VALUE) -1 else dp[amount]

How It Works

Key Insight

The minimum number of coins to make amount i can be found by trying each coin and taking the minimum of dp[i - coin] + 1 for all coins that don't exceed i. This builds up the solution from smaller amounts to the target amount.

The Algorithm

  • Initialize: Create a DP array of size amount + 1, filled with infinity. Set dp[0] = 0 (base case: zero coins needed for amount 0).
  • For each amount from 1 to target: Try each coin denomination.
  • If coin โ‰ค current amount: Calculate dp[i - coin] + 1 (use one coin and add the solution for the remaining amount).
  • Take minimum: Update dp[i] with the minimum of its current value and the new calculation.
  • Return result: If dp[amount] is still infinity, return -1 (impossible). Otherwise, return dp[amount].

Complexity

Time O(amount ร— coins.length)
Space O(amount)

We iterate through all amounts from 1 to the target, and for each amount, we try all coin denominations. This gives us O(amount ร— coins) time complexity. The space complexity is O(amount) for the DP array.