Dynamic Programming: Knapsack - Coin Change (Minimum Coins)
The following code attempts to solve the coin change minimum coins problem. Identify the line containing the subtle bug that causes incorrect results or infinite recursion for amount=0.
def coinChange(coins, amount):
def dfs(rem):
if rem == 0:
return 0
res = float('inf')
for coin in coins:
if rem - coin >= 0:
res = min(res, 1 + dfs(rem - coin))
return res
ans = dfs(amount)
return ans if ans != float('inf') else -1
