714258. Another Coin Change Problem

Medium

Another Coin Change Problem

Summary

Given a set of coin denominations and an amount, find the number of ways to make change for that amount using these coins. This problem involves dynamic programming, where we need to optimize the solution by breaking down the problem into smaller subproblems.

Detailed Explanation

The problem can be solved by creating a 2D array dp where dp[i][j] represents the number of ways to make change for j using coins up to denomination i. We initialize all values in dp as 0, except for dp[0][0] which is set to 1 (since there's one way to make no change).

We then iterate through each coin denomination from 0 to the maximum denomination, and for each denomination i, we iterate through each possible amount from 0 to the target amount. If the current amount is greater than or equal to the coin value i, we consider including this coin in our solution.

For each amount j, if it's not less than the coin value i, we calculate the number of ways to make change for j-i using coins up to denomination i-1, and add this value to the current count. We then update dp[i][j] with the total count.

Finally, we return dp[max_denomination][target_amount] as the result, which represents the number of ways to make change for the target amount using all available coin denominations.

Here's a step-by-step breakdown:

  dp = [[0 for _ in range(target_amount + 1)] for _ in range(max_denomination + 1)]
  
  for i in range(max_denomination + 1):
    for j in range(target_amount + 1):
      if j < i:
        dp[i][j] = 0
      elif j == i:
        dp[i][j] = 1
      else:
        dp[i][j] = dp[i-1][j] if j >= i else 0
  
  return dp[max_denomination][target_amount]

Time complexity: O(max_denomination * target_amount) Space complexity: O(max_denomination * target_amount)

Optimized Solutions

Java

View on GeeksforGeeks
public int coinChange(int[] coins, int amount) {
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);
    dp[0] = 0;
    
    for (int i = 0; i <= amount; i++) {
        for (int j : coins) {
            if (i >= j) {
                dp[i] = Math.min(dp[i], dp[i - j] + 1);
            }
        }
    }
    
    return dp[amount] > amount ? -1 : dp[amount];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.