LeetCode 322: Coin Change Solution

Master LeetCode problem 322 (Coin Change), 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.

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will create an array dp where dp[i] represents the fewest number of coins needed to make up the amount i. We initialize dp[0] to 0 and all other elements to a value greater than the amount (to represent infinity). Then, for each coin denomination, we iterate through the amounts from the coin value to the target amount, updating the dp array with the minimum number of coins needed for each amount. The final answer will be dp[amount] if it is less than the initial value we set or -1 if it remains unchanged.

Time complexity: O(amount * number of coins)
Space complexity: O(amount)

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 322 (Coin Change)?

This page provides optimized solutions for LeetCode problem 322 (Coin Change) 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 322 (Coin Change)?

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

Can I run code for LeetCode 322 on DevExCode?

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

Back to LeetCode Solutions