Skip to content

Commit fbfc9f1

Browse files
committed
Python Solution for Coin Change Problem in DP
1 parent 1c419d5 commit fbfc9f1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Dynamic Programming/CoinChange.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# https://leetcode.com/problems/coin-change/
2+
3+
#### In the given problem , we are supposed to find minimum number of coins to get the sum equal to the amount given
4+
5+
#### For given example
6+
# - Input :
7+
8+
# 1. coins = [7 , 5 , 1]
9+
# 2. amount = 18
10+
11+
# - O/p :
12+
# 4
13+
14+
# We can achieve 18 by
15+
# - 2 Coins of 5
16+
# - 1 coin of 7
17+
# - 1 coin of 1
18+
# - Sum = 4
19+
20+
# 18 can be achieved by various combinations of 7 , 5 , 1
21+
22+
# https://ibb.co/TtcVRYx
23+
24+
# Refer the image above
25+
26+
# Lets call 11 , 13 , 17 , 6 , 12 , 10 ... as subSums
27+
28+
# As shown in the image above , 6 has been calculated previously and later on 6 is required in latter part .
29+
# Instead of computing it again , we can store the value for 6 i.e 2 (1 coin of 5 and 1 coin of 1)
30+
31+
# As we need to store the value of recursion ie. Subsums in a memory , hence we choose DP here
32+
33+
# Consider a list op = [] with size equal to the amount
34+
35+
# op[] stores the number of coins required for each number from 1, 2 ,...amount
36+
# We are supposed to return op[amount]
37+
38+
# In this case op[18] returns the minimum coins required to produce the sum 18
39+
40+
41+
class Solution(object):
42+
def coinChange(self, coins, amount):
43+
"""
44+
:type coins: List[int]
45+
:type amount: int
46+
:rtype: int
47+
"""
48+
op = [amount+1] * (amount+1)
49+
op[0] = 0
50+
for i in xrange(1, amount+1):
51+
for c in coins:
52+
if i >= c:
53+
op[i] = min(op[i], op[i-c] + 1)
54+
55+
if op[amount] >= amount+1:
56+
return -1
57+
return op[amount]
58+
59+

0 commit comments

Comments
 (0)