Coin Change LeetCode solution in Python

1
class Solution:
2
def coinChange(self, coins: List[int], amount: int) -> int:
3
numCoins = len(coins)
4

5
# Values in this array equal the number of coins needed to achieve the cost of the index
6
minCoins = [amount + 1] * (amount + 1)
7
minCoins[0] = 0
8

9
# Loop through every needed amount
10
for i in range(amount + 1):
11
# Loop through every coin value
12
for coin in coins:
13
# Check that the coin is not bigger than the current amount
14
if coin <= i:
15
# minCoins[i]: number of coins needed to make amount i
16
# minCoins[i-coin]: number of coins needed to make the amount before adding
17
# the current coin to it (+1 to add the current coin)
18
minCoins[i] = min(minCoins[i], minCoins[i - coin] + 1)
19

20
# Check if any combination of coins was found to create the amount
21
if minCoins[amount] == amount + 1:
22
return -1
23

24
# Return the optimal number of coins to create the amount
25
return minCoins[amount]

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0