CodexBloom - Programming Q&A Platform

Finding the Minimum Number of Coins for Change Using Dynamic Programming in Python - Edge Cases Not Handled Correctly

πŸ‘€ Views: 82 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
python dynamic-programming algorithms Python

I'm attempting to set up I'm trying to configure I've spent hours debugging this and I'm trying to implement a dynamic programming solution to find the minimum number of coins needed to make up a given amount... I'm using Python 3.8 and I'm working with issues with specific edge cases, especially when the amount is less than the smallest denomination available. My implementation is supposed to return -1 in such cases, but it still returns a count of coins instead. Here’s the code I’ve written: ```python def min_coins(coins, amount): dp = [float('inf')] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != float('inf') else -1 ``` I initially thought this code would handle all cases, but when I tried to run it with the following examples: ```python print(min_coins([5, 10], 3)) # Should return -1 print(min_coins([1, 3, 4], 6)) # Should return 2 (2 coins of 3) ``` The first call returns 1, which is incorrect as it should indicate that it's impossible to make change for 3 using the provided denominations. I've also checked the algorithm for other amounts and it works fine, but this edge case seems to be a question. Any advice on what I might be missing or how to properly handle this situation? Thanks in advance! I'm working on a application that needs to handle this. Has anyone else encountered this? I appreciate any insights!