Skip to content

Commit 34b166d

Browse files
authored
Update Coin Change - Leetcode 322.py
1 parent e52c693 commit 34b166d

File tree

1 file changed

+46
-11
lines changed

1 file changed

+46
-11
lines changed

Coin Change - Leetcode 322.py

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,54 @@
11
class Solution:
22
def coinChange(self, coins: List[int], amount: int) -> int:
3-
n = len(coins)
3+
# Top Down DP (Memoization)
4+
# Time: O(Coins * Amount)
5+
# Space: O(Amount)
6+
coins.sort()
7+
memo = {0:0}
8+
9+
def min_coins(amt):
10+
if amt in memo:
11+
return memo[amt]
12+
13+
minn = float('inf')
14+
for coin in coins:
15+
diff = amt - coin
16+
if diff < 0:
17+
break
18+
minn = min(minn, 1 + min_coins(diff))
19+
20+
memo[amt] = minn
21+
return minn
22+
23+
result = min_coins(amount)
24+
if result < float('inf'):
25+
return result
26+
else:
27+
return -1
28+
29+
30+
31+
class Solution:
32+
def coinChange(self, coins: List[int], amount: int) -> int:
33+
# Bottom Up DP (Tabulation)
34+
# Time: O(Coins * Amount)
35+
# Space: O(Amount)
36+
dp = [0] * (amount + 1)
437
coins.sort()
5-
dp = [float('inf')] * (amount + 1)
6-
dp[0] = 0
738

839
for i in range(1, amount+1):
40+
minn = float('inf')
41+
942
for coin in coins:
10-
difference = i - coin
11-
if difference < 0:
43+
diff = i - coin
44+
if diff < 0:
1245
break
13-
dp[i] = min(dp[i], 1+dp[difference])
14-
46+
minn = min(minn, dp[diff] + 1)
47+
48+
dp[i] = minn
1549

16-
return dp[amount] if dp[amount] < float('inf') else -1
17-
# Let C be the number of coins and A be the amount.
18-
# Time Complexity: O(C * Amount)
19-
# Space Complexity: O(Amount)
50+
if dp[amount] < float('inf'):
51+
return dp[amount]
52+
else:
53+
return -1
54+

0 commit comments

Comments
 (0)