322. Coin Change

Description

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.

You may assume that you have an infinite number of each kind of coin.

Constraints

  • 1 <= coins.length <= 12

  • 1 <= coins[i] <= 231 - 1

  • 0 <= amount <= 104

Approach

  • GeeksforGeeks

  • ProgramCreek

  • YouTube

Examples

Input: coins = [1,2,5], amount = 11

Output: 3

Explanation: 11 = 5 + 5 + 1

Solutions

/**
 * Time complexity : O(S*n). where S is the amount. On each step the 
 *    algorithm finds the next F(i) in n iterations, where 1 < i <= S. 
 *    Therefore in total the iterations are S*n.
 * Space complexity : O(S). We use extra space for the memoization table.
 */

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

Follow up

Last updated

Was this helpful?