Advertisement
imashutosh51

Coin change with minimum coins

Oct 8th, 2022 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. '''
  2. Logic:
  3. We will traverse the whole amount from 0.
  4. and for every amount,we will traverse all the coins.
  5. if current amount-current coin>=0 and check for amount form by
  6. (current amount-current coin) in dp table,update the minimum of both.
  7.  
  8. dp[i] stores the minimum number of coins needed for amount i.
  9. We initialize with infinity as an impossible high value (worse than any valid answer).
  10. For each amount i, we check if we can reach it by adding a coin to a smaller amount i - coin.
  11. If dp[amount] remains unchanged, it means there's no valid way to make up the amount.
  12.  
  13. '''
  14.  
  15. class Solution:
  16.     def coinChange(self, coins: List[int], amount: int) -> int:
  17.         dp=[math.inf]*(amount+1)
  18.         dp[0]=0
  19.         for i in range(1,amount+1):
  20.             for coin in coins:
  21.                 if i-coin>=0:
  22.                     dp[i]=min(dp[i],dp[i-coin]+1)
  23.         if dp[amount]==math.inf:
  24.             return -1
  25.         else:
  26.             return dp[amount]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement