Created
February 12, 2022 05:21
-
-
Save amarjitdhillon/9cf7180dc9ff4d2a6bd027e27db8e3e3 to your computer and use it in GitHub Desktop.
Coin Change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def coinChange(self, coins: List[int], amount: int) -> int: | |
# Create a dp array for 0 to amount (inclusive) with the max values | |
dp = [float('inf')] * (amount+1) | |
# Initialize the value of the dp array | |
dp[0] = 0 | |
# Let's compute dp array for all values from 1 to amount | |
for i in range(1, amount+1): | |
# We will consider all the coins and then take min from that | |
for coin in coins: | |
if i-coin >= 0: | |
dp[i] = min(dp[i], 1 + dp[i-coin]) | |
# After this loop is run, dp[amount] is our result given the fact that it's not infinity | |
# If it's inf, then we will return -1 | |
return dp[amount] if dp[amount] != float('inf') else -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment