Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 322: Coin Change

LeetCode 322 Solution 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)

LeetCode 322 Solutions in Java, C++, Python

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

Interactive Code Editor for LeetCode 322

Improve Your LeetCode 322 Solution

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

  • Add import statements 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.

Loading editor...

Related LeetCode Problems