# 322-coin-change Try it on leetcode ## Description

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.

 

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

 

Constraints:

## Solution(Python) ```Python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: return self.dp(coins, amount) # Time Complexity: O(S^n) # Space Complexity: O(n) def bruteforce(self, coins: List[int], amount: int) -> int: def coinchange(idx, coins, amount): if amount == 0: return 0 if idx < len(coins) and amount > 0: maxVal = amount / coins[idx] mincost = sys.maxsize for x in range(maxVal + 1): if amount >= x * coins[idx]: res = coinchange( idx + 1, coins, amount - x * coins[idx]) if res != -1: mincost = min(mincost, res + x) return mincost if mincost < sys.maxsize else -1 return -1 return coinchange(0, coins, amount) # Time Complexity: O(S*n) # Space Complexity: O(S) @cache def topdown(self, amount: int) -> int: if amount < 0: return -1 if amount == 0: return 0 min_ = sys.maxsize for coin in self.coins: res = self.topdown(amount - coin) if res >= 0 and res < min_: min_ = res + 1 return -1 if min_ == sys.maxsize else min_ # Time Complexity: O(S*n) # Space Complexity: O(S) def dp(self, coins: List[int], amount: int) -> int: dp = [float("inf")] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != float("inf") else -1 ```