nathanwailes

Coin change - DP

Jun 9th, 2024
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. """
  2. 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.
  3.  
  4. This implementation ensures that the problem is solved in a time-efficient manner using dynamic programming, with a time complexity of O(amount * n) where n is the number of different coins.
  5. """
  6.  
  7. def coinChange(coins, amount):
  8.     # Initialize DP array with a large number, amount + 1 is a safe large number since we can't use more than amount coins.
  9.     dp = [amount + 1] * (amount + 1)
  10.    
  11.     # Base case: to make 0 amount, 0 coins are needed
  12.     dp[0] = 0
  13.    
  14.     # Loop through each amount from 1 to amount
  15.     for a in range(1, amount + 1):
  16.         # Loop through each coin
  17.         for coin in coins:
  18.             if a - coin >= 0:
  19.                 dp[a] = min(dp[a], dp[a - coin] + 1)
  20.    
  21.     # If dp[amount] is still amount + 1, it means it's not possible to form that amount
  22.     return dp[amount] if dp[amount] != amount + 1 else -1
  23.  
  24. # Example usage
  25. coins = [1, 2, 5]
  26. amount = 11
  27. print(coinChange(coins, amount))  # Output: 3 (11 = 5 + 5 + 1)
  28.  
Advertisement
Add Comment
Please, Sign In to add comment