imashutosh51

Coin change with minimum coins

Oct 8th, 2022 (edited)
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. '''
  2. Intuition:
  3. - We want the minimum number of coins needed to make every value from 0 to amount.
  4. - Let dp[x] = minimum coins required to make sum x.
  5. - Base case: dp[0] = 0 (0 amount needs 0 coins).
  6. - For every target sum i (1 to amount):
  7.    - Try using each coin.
  8.    - If we take coin, then the remaining sum is (i - coin).
  9.    - So candidate answer becomes: dp[i - coin] + 1
  10.    - Take the minimum over all coins.
  11.  
  12. - If dp[amount] stays infinity, it means no combination can form the amount.
  13.  
  14. Time Complexity: O(amount * len(coins))
  15. Space Complexity: O(amount)
  16. '''
  17. import math
  18. class Solution:
  19.     def coinChange(self, coins: List[int], amount: int) -> int:
  20.         dp=[inf]*(amount+1)
  21.         dp[0]=0
  22.         for i in range(1,amount+1):
  23.             for coin in coins:
  24.                 if i-coin>=0:
  25.                     dp[i]=min(dp[i],dp[i-coin]+1)
  26.  
  27.         if dp[amount]==inf:
  28.             return -1
  29.         else:
  30.             return dp[amount]
  31.  
  32.  
  33. #M-2
  34. import math
  35. def fun(n,rem,coins,dp):
  36.     if rem==0:
  37.         return 0
  38.     if n<0 or rem<0:
  39.         return math.inf
  40.  
  41.     if dp[n][rem]!=-1:
  42.         return dp[n][rem]
  43.     take=math.inf
  44.     if rem>=coins[n]:
  45.         take=1+fun(n,rem-coins[n],coins,dp)
  46.     not_take=fun(n-1,rem,coins,dp)
  47.     dp[n][rem]=min(take,not_take)
  48.     return dp[n][rem]
  49.  
  50. class Solution:
  51.     def coinChange(self, coins: List[int], amount: int) -> int:
  52.         dp=[[-1]*(amount+1) for _ in range(len(coins))]
  53.         n=len(coins)
  54.         ans=fun(n-1,amount,coins,dp)
  55.         return ans if ans!=math.inf else -1
  56.        
  57.        
Advertisement
Add Comment
Please, Sign In to add comment