322. Coin Change

You are given coins of different denominations and a total amount of money amount. Write a function to compute 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.

dynamic programming, iteration

class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] memo = new int[amount+1];
        for (int i=1; i<=amount; i++){
            for(int coin : coins){
                // check the conis in previous amounts
                if (i-coin>=0 && memo[i-coin]!=-1){
                    memo[i]= memo[i]>0? Math.min(memo[i], memo[i-coin]+1) : memo[i-coin]+1; 
                }
            }
            // make sure to invalid the amount if no coins match
            if (memo[i]==0) memo[i]=-1;
        }

        return memo[amount];
    }
}

Last updated