LeetCode 518: Coin Change II Solution

Master LeetCode problem 518 (Coin Change II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

518. Coin Change II

Problem Explanation

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)

Solution Code

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];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 518 (Coin Change II)?

This page provides optimized solutions for LeetCode problem 518 (Coin Change II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 518 (Coin Change II)?

The time complexity for LeetCode 518 (Coin Change II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 518 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 518 in Java, C++, or Python.

Back to LeetCode Solutions