Skip to content

Commit 233036e

Browse files
committed
add coin change solution
1 parent 9ac1802 commit 233036e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

coin-change/i-mprovising.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Time complexity O(len(coins) * amount)
3+
Space complexity O(amount)
4+
5+
Dynamic programming
6+
"""
7+
8+
class Solution:
9+
def coinChange(self, coins: List[int], amount: int) -> int:
10+
coins = sorted(coins)
11+
12+
if amount == 0 :
13+
return 0
14+
15+
dp = [0] + [-1 for _ in range(amount)]
16+
17+
for i in range(coins[0], amount+1):
18+
tmp = []
19+
for x in coins:
20+
if i - x >= 0:
21+
if dp[i - x] != -1:
22+
tmp.append(dp[i - x] + 1)
23+
if len(tmp) == 0:
24+
dp[i] = -1
25+
else:
26+
dp[i] = min(tmp)
27+
28+
if dp[-1] == 0:
29+
return -1
30+
return dp[-1]

0 commit comments

Comments
 (0)