Skip to content

Commit b20c1da

Browse files
committed
Interview Question - Minimum Coin Change - DP
1 parent 0c099f2 commit b20c1da

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

LeetCode/322.coin-change.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#
2+
# @lc app=leetcode id=322 lang=python3
3+
#
4+
# [322] Coin Change
5+
#
6+
7+
# @lc code=start
8+
INF = 10 ** 7
9+
class Solution:
10+
def coinChange(self, C: List[int], S: int) -> int:
11+
noCoins = len(C)
12+
dp = [[INF for _ in range(noCoins+1)] for _ in range(S+1)]
13+
# dp[i][j] is min coins needed to make sum "i" when first "j" coins are available
14+
dp[0][0] = 0 # no coin needed to make 0
15+
for i in range(0, S+1):
16+
for j in range(1, noCoins+1):
17+
curCoin = C[j-1] # 0-based indexing
18+
19+
# Case A: I don't take jth coin
20+
dp[i][j] = dp[i][j-1]
21+
22+
# Case B: I take jth coin
23+
if curCoin <= i:
24+
dp[i][j] = min(dp[i][j], 1 + dp[i-curCoin][j])
25+
return dp[S][noCoins] if dp[S][noCoins] != INF else -1
26+
27+
# @lc code=end
28+

0 commit comments

Comments
 (0)