imashutosh51

Coin Change

Mar 6th, 2026
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. '''
  2. Unbounded Knapsack: here find the target by choosing the coins of the array but you can choose multiple times the same coin.
  3. In the dp table here, rows denotes all the indices of the coins, and column denotes the target remaining so dp[i][j] says minimum
  4. number of coins possible to get the jth target but by using 0->ith coins.
  5.  
  6. Base Cases:
  7. 1.if target_remaining==0, means you achieved your target, so just return 0.
  8. 2.if i<0, means you didn't achieve the target even after exhausing all the coins combinations so we have to ignore this case completely
  9. so to do that return inf because we are comparing the minimum of take and not_take so this case will automatically eliminated.
  10. 3.initialise take with inf because if take case is not there, then you should completely ignore this case.
  11. '''
  12. import math
  13. def fun(arr,i,cur_remaining, dp):
  14.     if cur_remaining==0:
  15.         return 0
  16.     if i<0:
  17.         return math.inf
  18.     if dp[i][cur_remaining]!=-1:
  19.         return dp[i][cur_remaining]
  20.     coin=arr[i]
  21.     take=math.inf
  22.     if cur_remaining>=coin:
  23.         take=1+fun(arr,i,cur_remaining-coin, dp)
  24.     not_take=fun(arr,i-1,cur_remaining,dp)
  25.     dp[i][cur_remaining]=min(take,not_take)
  26.     return dp[i][cur_remaining]
  27.  
  28.  
  29. class Solution:
  30.     def coinChange(self, coins: List[int], amount: int) -> int:
  31.         dp=[[-1]*(amount+1) for _ in range(len(coins))]
  32.         ans=fun(coins,len(coins)-1,amount,dp)
  33.         return ans if ans!=math.inf else -1
  34.        
Advertisement
Add Comment
Please, Sign In to add comment