|
2 | 2 |
|
3 | 3 |
|
4 | 4 | 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, |
7 | 14 | 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) |
10 | 27 |
|
11 | 28 |
|
12 | 29 | 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