Continue learning
Practice related DSA questions in the same topic.
Use unlimited copies of the positive denominations to make target exactly. Return the minimum number of coins, or -1.
Use unlimited copies of the positive denominations to make target exactly. Return the minimum number of coins, or -1.
def solve(values, target): dp = [0] * ((target + 1)) amount = 1 while (amount <= target): dp[amount] = (target + 1) i = 0 while (i < len(values)): coin = values[i] if (coin <= amount): dp[amount] = min(dp[amount], (dp[(amount - coin)] + 1)) i = (i + 1) amount = (amount + 1) if (dp[target] > target): return -1 return dp[target]Try a final coin of 1 for amount 1.
Try a final coin of 1 for amount 1.
A change counter writes the minimum number of coins on each smaller amount card.
For each amount, try each possible last coin and keep the shortest reachable predecessor plus one.
O(t × n) time · O(t) auxiliary space
Worked example · {"values":[1,3,4],"target":6} ⇒ 2
Edge case 1 · {"values":[4,6],"target":5} ⇒ -1
Edge case 2 · {"values":[],"target":0} ⇒ 0
Edge case 3 · {"values":[],"target":3} ⇒ -1
Taking the largest coin first can fail for denominations such as 1, 3, 4.
How would you reconstruct the actual chosen coins?