šŸ”— LeetCode

Coin Change

Mediumdynamic programmingAmazonMicrosoftGoogleMetaBloomberg

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.


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

Examples

Input:coins = [1,2,5], amount = 11
Output:3
Explanation:11 = 5 + 5 + 1 (3 coins total).
Input:coins = [2], amount = 3
Output:-1
Explanation:Amount 3 cannot be made with only 2-cent coins.
Input:coins = [1], amount = 0
Output:0
Explanation:Amount 0 requires 0 coins.
Input:coins = [1,2,5], amount = 5
Output:1
Explanation:Amount 5 requires only 1 coin (5-cent coin). This matches the step-by-step dry-run visualization.

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

šŸ’” Hints

Hint 1

Think bottom-up: to make up amount i, consider taking coin c and adding 1 to the optimal solution for amount (i - c).

Hint 2

Initialize an array dp of size amount + 1 with Infinity. Base case is dp[0] = 0.

Hint 3

For each amount from 1 to amount, iterate over all coins that are <= current amount and take the minimum.

Algorithm Complexity

Official asymptotic Big-O runtime and auxiliary memory analysis

Quadratic
Algorithmic Approach

Bottom-up 1D dynamic programming. dp[i] represents the minimum coins needed for amount i. Transition: dp[i] = min(dp[i], dp[i - coin] + 1).

Time ComplexityO(amount * coins.length)
Why:

Iterates through each sub-amount from 1 to amount, trying each of the available coins in inner iteration in O(amount * coins.length).

Space ComplexityO(amount)
Why:

A 1D dynamic programming table of size (amount + 1) stores the minimum coin counts.

Big-O Growth CurveQuadratic (O(N²))
Execution time grows quadratically with nested iterations over the input.

šŸŒ Real-World Use Cases

StripeCurrency Exchange & Payout Denomination Optimization

Determining the minimal set of bill/token denominations required to satisfy merchant cash transfers using 1D dynamic programming.

šŸ” Dry Run

Solutionā± O(amount * coins.length) | šŸ’¾ O(amount)
Dynamic Programming
1D DP Array
Formula:Base case: dp[0] = 0
Current Cell
Subproblem Read
Computed
012345
dp
0
āˆž
āˆž
āˆž
āˆž
āˆž
Line3
amount=5number
dp[0]=0number

Initialize dp table of size 6 for amount = 5. Base case: dp[0] = 0 coins needed for amount 0.