Coders Crushby Napplied AI
Back to DSA Problems
MediumLeetCode #322Dynamic Programming

Coin Change

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.

Constraints
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • AI Discovery

Coders Crush by Napplied AI - Built for engineers preparing for FAANG/MAANG interviews

1 <= coins.length <= 12, 1 <= coins[i] <= 2^31 - 1, 0 <= amount <= 10^4
Examples
Input: coins = [1,2,5], amount = 11
Output: 3
11 = 5 + 5 + 1
Solution

Approach

DP where dp[i] = minimum coins to make amount i. For each amount, try each coin: dp[i] = min(dp[i], dp[i - coin] + 1).

def coinChange(coins, amount):
    dp = [float("inf")] * (amount + 1)
    dp[0] = 0
    for i in range(1, amount + 1):
        for coin in coins:
            if coin <= i:
                dp[i] = min(dp[i], dp[i - coin] + 1)
    return dp[amount] if dp[amount] != float("inf") else -1
Complexity
Time:O(amount * n)
Space:O(amount)
Hints
  • 1.dp[i] = min coins for amount i
  • 2.Try using each coin as the last coin
  • 3.Initialize dp[0] = 0
Asked at
GoogleAmazonAppleMicrosoftGoldman Sachs