Coin change#

Levels: level-3
Algorithms: dynamic-programming

LeetCode

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.

Note:

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

Examples#

1Input: coins = [1, 2, 5], amount = 11
2Output: 3
3Explanation: 11 = 5 + 5 + 1
1Input: coins = [2], amount = 3
2Output: -1

Python Solution#

 1class Solution(object):
 2    def coinChange(self, coins, amount):
 3        """
 4        :type coins: List[int]
 5        :type amount: int
 6        :rtype: int
 7        """
 8        # Start with a dp array of size amount + 1. 
 9        # Use amount + 1 as the "max" value. 
10        rs = [amount + 1] * (amount + 1)
11        # No coin needed for amount zero
12        rs[0] = 0
13        # Calculate min counts needed for each target upto amount.
14        for i in range(1, amount + 1):
15            # Check for each available denomination
16            for c in coins:
17                if i >= c:
18                    # Coins needed for target amount i is
19                    # the min of (current calculated min number of coins)
20                    # and (coins needed for i - c target amount + 1) 
21                    rs[i] = min(rs[i], rs[i - c] + 1)
22
23        if rs[amount] == amount + 1:
24            # return -1 if calculated n coins is the "max" value set initially.
25            return -1
26        return rs[amount]
27
28
29tm = [
30    ([1, 2, 5], 11, 3),
31    ([2], 3, -1),
32    ([], 11, -1),
33]
34
35if __name__ == "__main__":
36
37    sol1 = Solution()
38
39    for idx, nin in enumerate(tm):
40        resout = sol1.coinChange(nin[0], nin[1])
41        print(nin, resout, resout == nin[-1])