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
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] = min coins needed for amount i. For each coin, update reachable amounts.
Implementation
def coinChange(coins, amount):
dp = [float("inf")] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float("inf") else -1Complexity Analysis
Time Complexity
O(amount * n)Space Complexity
O(amount)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
Google