Imagine you have an unlimited supply of coins of different denominations and you want to pay a certain amount using the fewest coins possible.
Given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money, return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
1 ≤ coins.length ≤ 121 ≤ coins[i] ≤ 2^31 - 10 ≤ amount ≤ 10^4
Edge cases: amount = 0 → output 0 (no coins needed)coins = [1], amount = 0 → output 0 (zero amount)coins = [1], amount = 1 → output 1 (single coin equals amount)
def coinChange(coins: list[int], amount: int) -> int:public int coinChange(int[] coins, int amount)int coinChange(vector<int>& coins, int amount)function coinChange(coins, amount)
def coinChange(coins, amount):
# Write your solution here
pass
class Solution {
public int coinChange(int[] coins, int amount) {
// Write your solution here
return -1;
}
}
#include <vector>
using namespace std;
int coinChange(vector<int>& coins, int amount) {
// Write your solution here
return -1;
}
function coinChange(coins, amount) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: -1 for amount=11 with coins=[1,2,5]Not considering all coin combinations or incorrect DP initialization.✅ Initialize dp array with large values and update dp[amt] = min(dp[amt], 1 + dp[amt - coin]) for all coins and amounts.
Wrong: 3 for amount=3 with coins=[2,5]Incorrectly assuming partial sums or using greedy approach that fails for impossible amounts.✅ Return -1 if dp[amount] remains infinity after DP computation.
Wrong: 1 for amount=3 with coins=[2]Confusing 0/1 knapsack with unbounded knapsack, allowing only one coin usage incorrectly.✅ Allow repeated use of coins by iterating amounts from coin to amount and updating dp accordingly.
Wrong: 4 for amount=7 with coins=[1,3,4]Greedy approach picking largest coin first without checking all combinations.✅ Use DP to consider all coins for each amount, not just greedy picks.
Wrong: TLE on large inputUsing brute force recursion without memoization or DP.✅ Implement bottom-up or top-down DP with memoization to achieve O(n*amount) time.