|
1 | 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 |
| 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 |
13 | 16 | """ |
14 | 17 |
|
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: |
19 | 19 | """ |
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. |
22 | 21 |
|
23 | 22 | 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. |
26 | 25 |
|
27 | 26 | 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 |
29 | 36 | """ |
30 | 37 | dp = [float("inf")] * (amount + 1) |
31 | 38 | dp[0] = 0 |
32 | 39 |
|
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) |
39 | 44 |
|
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