Skip to content

Commit ed63bf7

Browse files
committed
Add Coin Change algorithm using dynamic programming
1 parent 788d95b commit ed63bf7

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

dynamic_programming/coin_change.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Coin Change Problem - Dynamic Programming Approach
3+
--------------------------------------------------
4+
5+
Given a list of coin denominations and a target amount,
6+
this function returns the minimum number of coins needed
7+
to make up that amount. If it's not possible, returns -1.
8+
9+
Example:
10+
>>> coin_change([1, 2, 5], 11)
11+
3
12+
# Explanation: 11 = 5 + 5 + 1
13+
"""
14+
15+
from typing import List
16+
17+
18+
def coin_change(coins: List[int], amount: int) -> int:
19+
"""
20+
Calculate the minimum number of coins required
21+
to make up the given amount using dynamic programming.
22+
23+
Args:
24+
coins (List[int]): List of coin denominations.
25+
amount (int): The target amount.
26+
27+
Returns:
28+
int: Minimum number of coins required, or -1 if not possible.
29+
"""
30+
dp = [float("inf")] * (amount + 1)
31+
dp[0] = 0
32+
33+
for coin in coins:
34+
for i in range(coin, amount + 1):
35+
dp[i] = min(dp[i], dp[i - coin] + 1)
36+
37+
return dp[amount] if dp[amount] != float("inf") else -1
38+
39+
40+
if __name__ == "__main__":
41+
coins = [1, 2, 5]
42+
amount = 11
43+
print(f"Minimum coins required: {coin_change(coins, amount)}")

0 commit comments

Comments
 (0)