Skip to content

Commit 2c2f9e2

Browse files
authored
Create 322_Coin_Change.md
1 parent 28b0b6e commit 2c2f9e2

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

322_Coin_Change.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
2+
Return 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.
3+
You may assume that you have an infinite number of each kind of coin.
4+
5+
```
6+
Example 1:
7+
8+
Input: coins = [1,2,5], amount = 11
9+
Output: 3
10+
Explanation: 11 = 5 + 5 + 1
11+
Example 2:
12+
13+
Input: coins = [2], amount = 3
14+
Output: -1
15+
Example 3:
16+
17+
Input: coins = [1], amount = 0
18+
Output: 0
19+
Example 4:
20+
21+
Input: coins = [1], amount = 1
22+
Output: 1
23+
Example 5:
24+
25+
Input: coins = [1], amount = 2
26+
Output: 2
27+
28+
29+
Constraints:
30+
31+
1 <= coins.length <= 12
32+
1 <= coins[i] <= 231 - 1
33+
0 <= amount <= 104
34+
```
35+
36+
37+
```python
38+
def coinChange(self, coins: List[int], amount: int) -> int:
39+
40+
dp = [float('inf')] * (amount+1)
41+
dp[0] = 0
42+
for c in coins:
43+
for i in range(1, len(dp)):
44+
45+
if i>=c:
46+
dp[i] = min(dp[i], dp[i-c]+1)
47+
48+
if dp[-1] == float('inf'):
49+
return -1
50+
51+
# print(dp)
52+
return dp[-1]
53+
```
54+
55+
```
56+
Runtime: 1304 ms, faster than 58.25% of Python3 online submissions for Coin Change.
57+
Memory Usage: 14.6 MB, less than 53.75% of Python3 online submissions for Coin Change.
58+
```

0 commit comments

Comments
 (0)