Skip to content

Commit 62c736a

Browse files
committed
[main] added mincoins
1 parent 9da952d commit 62c736a

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

pythonProblems/dp/mincoins.py

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,33 @@
22

33

44
def min_coins(n: int, coins: List[int]):
5-
dp = [0] * n
6-
for i in range(n): # iterate through all the potential targets 0...n
5+
"""_summary_
6+
7+
Args:
8+
n (int): _description_
9+
coins (List[int]): _description_
10+
"""
11+
dp = [0] + ([float('inf')] * n)
12+
for i in range(n + 1): # iterate through all the potential coin value targets 0...n
13+
# iterate through all potential coins in the list and apply it to the sub-problems,
714
for j in range(len(coins)):
8-
dp[i] = min(dp[i], dp[i - j]) + 1
9-
return min(dp)
15+
# checking if the subproblem before it has less steps, then add one to the final result
16+
# checking if the current target - the coin we're on right now has been solved,
17+
if (i - coins[j]) < 0:
18+
# if it has not, then we continue
19+
continue
20+
# dp[i] represents the current potential target coin value
21+
# dp[i - coins[j]] represents the subproblem of the potential target coin value - the current coin
22+
# check the current target we're on, check if the current target has less steps
23+
dp[i] = min(dp[i], dp[i - coins[j]] + 1)
24+
# then the subproblem of the current target - the coin we're on currently (aka previous subproblem), then add one to that result
25+
# because we are evaluating a previous subproblem and in order to reach the current target we add one step to it.
26+
print(dp[n] if dp[n] != float('inf') else -1)
1027

1128

1229
if __name__ == '__main__':
13-
coins = [1, 5, 7]
14-
target = 11
15-
print(min_coins(target, coins))
30+
first_line = input()
31+
target = int(first_line.split(" ")[1])
32+
arr_line = input()
33+
arr = [int(x) for x in arr_line.split(" ")]
34+
min_coins(target, arr)

0 commit comments

Comments
 (0)