All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0301_0400.s0322_coin_change.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0301_0400.s0322_coin_change;

// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Dynamic_Programming
// #Breadth_First_Search #Algorithm_II_Day_18_Dynamic_Programming #Dynamic_Programming_I_Day_20
// #Level_2_Day_12_Dynamic_Programming #Big_O_Time_O(m*n)_Space_O(amount)
// #2022_07_09_Time_17_ms_(91.77%)_Space_41.8_MB_(95.50%)

/**
 * 322 - Coin Change\.
 *
 * Medium
 *
 * You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
 *
 * Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
 *
 * You may assume that you have an infinite number of each kind of coin.
 *
 * **Example 1:**
 *
 * **Input:** coins = [1,2,5], amount = 11
 *
 * **Output:** 3
 *
 * **Explanation:** 11 = 5 + 5 + 1 
 *
 * **Example 2:**
 *
 * **Input:** coins = [2], amount = 3
 *
 * **Output:** -1 
 *
 * **Example 3:**
 *
 * **Input:** coins = [1], amount = 0
 *
 * **Output:** 0 
 *
 * **Constraints:**
 *
 * *   `1 <= coins.length <= 12`
 * *   1 <= coins[i] <= 231 - 1
 * *   0 <= amount <= 104
**/
public class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for (int coin : coins) {
            for (int i = coin; i <= amount; i++) {
                int prev = dp[i - coin];
                if (prev > 0) {
                    if (dp[i] == 0) {
                        dp[i] = prev + 1;
                    } else {
                        dp[i] = Math.min(dp[i], prev + 1);
                    }
                }
            }
        }
        return dp[amount] - 1;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy