Skip to content

Commit 172f1ba

Browse files
committed
Fix: Update Coin Change Dynamic Programming algorithm to use modern type hints and ensure integer return
1 parent 29a0fee commit 172f1ba

File tree

1 file changed

+33
-30
lines changed

1 file changed

+33
-30
lines changed

dynamic_programming/coin_change.py

Lines changed: 33 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,46 @@
11
"""
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
2+
Coin Change - Dynamic Programming Algorithm
3+
4+
This module implements the classic coin change problem:
5+
finding the minimum number of coins required to make up a given amount.
6+
7+
Doctests:
8+
>>> coin_change([1, 2, 5], 11)
9+
3
10+
>>> coin_change([2], 3)
11+
-1
12+
>>> coin_change([1], 0)
13+
0
14+
>>> coin_change([1, 2, 5], 100)
15+
20
1316
"""
1417

15-
from typing import List
16-
17-
18-
def coin_change(coins: List[int], amount: int) -> int:
18+
def coin_change(coins: list[int], amount: int) -> int:
1919
"""
20-
Calculate the minimum number of coins required
21-
to make up the given amount using dynamic programming.
20+
Calculate the minimum number of coins required to make up the given amount.
2221
2322
Args:
24-
coins (List[int]): List of coin denominations.
25-
amount (int): The target amount.
23+
coins (list[int]): List of coin denominations.
24+
amount (int): Total amount to make.
2625
2726
Returns:
28-
int: Minimum number of coins required, or -1 if not possible.
27+
int: Minimum number of coins needed to make up the amount,
28+
or -1 if it's not possible.
29+
30+
>>> coin_change([1, 2, 5], 11)
31+
3
32+
>>> coin_change([2], 3)
33+
-1
34+
>>> coin_change([1], 0)
35+
0
2936
"""
3037
dp = [float("inf")] * (amount + 1)
3138
dp[0] = 0
3239

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-
40+
for i in range(1, amount + 1):
41+
for coin in coins:
42+
if i - coin >= 0:
43+
dp[i] = min(dp[i], dp[i - coin] + 1)
3944

40-
if __name__ == "__main__":
41-
coins = [1, 2, 5]
42-
amount = 11
43-
print(f"Minimum coins required: {coin_change(coins, amount)}")
45+
result = dp[amount]
46+
return result if result != float("inf") else -1

0 commit comments

Comments
 (0)