Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

518. Coin Change II

Explanation

To solve this problem, we can use dynamic programming. We will create a 1D array dp where dp[i] represents the number of combinations to make up amount i. We initialize dp[0] as 1, since there is one way to make up amount 0, which is by using no coins. Then, for each coin, we iterate through all amounts from the coin value to the target amount and update the number of combinations accordingly.

Algorithm:

  1. Initialize a 1D array dp of size amount + 1 with all values set to 0, except dp[0] = 1.
  2. Iterate through each coin in the coins array.
  3. For each coin, iterate through all amounts from the coin value to the target amount.
  4. Update dp[j] = dp[j] + dp[j - coin] to accumulate the number of combinations.

Time Complexity: O(amount * n), where n is the number of coins Space Complexity: O(amount)

class Solution {
    public int change(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;

        for (int coin : coins) {
            for (int j = coin; j <= amount; j++) {
                dp[j] += dp[j - coin];
            }
        }

        return dp[amount];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.