Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions dynamic_programming/coin_change.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
Coin Change Problem - Dynamic Programming Approach
--------------------------------------------------

Given a list of coin denominations and a target amount,
this function returns the minimum number of coins needed
to make up that amount. If it's not possible, returns -1.

Example:
>>> coin_change([1, 2, 5], 11)
3
# Explanation: 11 = 5 + 5 + 1
"""

from typing import List

Check failure on line 15 in dynamic_programming/coin_change.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

dynamic_programming/coin_change.py:15:1: UP035 `typing.List` is deprecated, use `list` instead


def coin_change(coins: List[int], amount: int) -> int:

Check failure on line 18 in dynamic_programming/coin_change.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

dynamic_programming/coin_change.py:18:24: UP006 Use `list` instead of `List` for type annotation
"""
Calculate the minimum number of coins required
to make up the given amount using dynamic programming.

Args:
coins (List[int]): List of coin denominations.
amount (int): The target amount.

Returns:
int: Minimum number of coins required, or -1 if not possible.
"""
dp = [float("inf")] * (amount + 1)
dp[0] = 0

for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)

return dp[amount] if dp[amount] != float("inf") else -1


if __name__ == "__main__":
coins = [1, 2, 5]
amount = 11
print(f"Minimum coins required: {coin_change(coins, amount)}")
153 changes: 0 additions & 153 deletions dynamic_programming/knapsack.py

This file was deleted.

Loading