Skip to content

Commit 65e96d0

Browse files
committed
Add solution for Coin Change problem using dynamic programming
1 parent c159fc1 commit 65e96d0

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

β€Žcoin-change/gcount85.pyβ€Ž

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
# Intuition
3+
dp[n]은 n원을 λ§Œλ“œλŠ”λ° ν•„μš”ν•œ μ΅œμ†Œ 동전 개수
4+
e.g. n = 11일 λ•Œ, 11원을 λ§Œλ“€κΈ° μœ„ν•œ μ΅œμ†Œ 동전 κ°œμˆ˜λŠ” 11μ—μ„œ coins의 μ›μ†Œλ₯Ό λΊ€ dp κ°’ + 1이닀.
5+
6+
# Complexity
7+
- Time complexity: O(amount * coins.length)인데, coins λ°°μ—΄ 길이가 μƒμˆ˜λΌμ„œ λ¬΄μ‹œ => O(amount)
8+
9+
- Space complexity: dp λ°°μ—΄ μƒμ„±μœΌλ‘œ O(amount)
10+
"""
11+
12+
13+
class Solution:
14+
def coinChange(self, coins: list[int], amount: int) -> int:
15+
coins.sort()
16+
INF = float("inf")
17+
dp = [INF] * (amount + 1)
18+
dp[0] = 0
19+
for i in range(amount + 1):
20+
if dp[i] == INF:
21+
continue
22+
for c in coins:
23+
if i + c > amount:
24+
break
25+
dp[i + c] = min(dp[i + c], dp[i] + 1)
26+
return dp[-1] if dp[-1] != INF else -1

0 commit comments

Comments
Β (0)