[LeetCode] 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.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.

Though process:
Suppose we have coins [c1, c2, c3, . . . , cn]. The sub-problem is to find the fewest number of coins to make [amount - c1, amount - c2, amount - c3, . . . , amount - cn]. And our dynamic programming function is:
f[i] = min(f[i - coins[0]], f[i - coins[1]], f[i - coins[2]], . . . , f[i - coins[n]]) + 1

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] f = new int[amount + 1];
        
        for (int i = 1; i <= amount; i++) {
            int min = Integer.MAX_VALUE;
            
            for (int coin : coins) {
                if (i - coin >= 0 && f[i - coin] != -1) {
                    int num = f[i - coin] + 1;
                    
                    if (num < min) {
                        min = num;
                    }
                }
            }
            
            f[i] = min == Integer.MAX_VALUE ? -1 : min;
        }
        
        return f[amount];
    }
}

Time complexity:

Say the number of coins = a and amount = b. The time complexity is O(ab).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[HackerRank] Roads and Libraries

[LeetCode] 631. Design Excel Sum Formula