Skip to content

Commit 77d44f0

Browse files
committed
added Coin Change DP
1 parent 10293f7 commit 77d44f0

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Coin Change
2+
3+
[Leetcode Link](https://leetcode.com/problems/coin-change/)
4+
5+
## Problem:
6+
7+
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
8+
9+
You may assume that you have an infinite number of each kind of coin.
10+
11+
## Example:
12+
13+
```
14+
Input: coins = [1,2,5], amount = 11
15+
Output: 3
16+
Explanation: 11 = 5 + 5 + 1
17+
```
18+
19+
```
20+
Input: coins = [2], amount = 3
21+
Output: -1
22+
```
23+
24+
```
25+
Input: coins = [1], amount = 0
26+
Output: 0
27+
```
28+
29+
```
30+
Input: coins = [1], amount = 1
31+
Output: 1
32+
```
33+
34+
## Note:
35+
36+
- 1 <= coins.length <= 12
37+
- 1 <= coins[i] <= 231 - 1
38+
- 0 <= amount <= 104
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def coinChange(self, coins: List[int], amount: int) -> int:
6+
dp = [float('inf') for _ in range(amount+1)]
7+
dp[0] = 0
8+
for coin in coins:
9+
for amt in range(1, amount+1):
10+
if coin <= amt:
11+
dp[amt] = min(dp[amt], 1 + dp[amt - coin])
12+
print(dp)
13+
return dp[-1] if dp[-1] != float('inf') else -1
14+
15+
16+
sol = Solution()
17+
coins = [1, 2, 5]
18+
amount = 11
19+
print(sol.coinChange(coins, amount))

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Languages used: Java and Python
5959
### [Dynamic Programming](./DynamicProgramming)
6060

6161
- [Climbing Stairs](DynamicProgramming/ClimbingStairs)
62+
- [Coin Change](DynamicProgramming/CoinChange)
6263
- [Count Square With Ones](DynamicProgramming/CountSquareWithOnes)
6364
- [House Robber](DynamicProgramming/HouseRobber)
6465
- [Longest Increasing Subsequence](DynamicProgramming/LongestIncreasingSubsequence)

0 commit comments

Comments
 (0)