1 minute read

Coin change.

Problem description

Taken directly from LeetCode.

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

Solution type

Caching, DP flavor.

Solution

def coinChange(self, coins: List[int], amount: int) -> int:
    memo = [sys.maxsize] * (amount + 1)
    memo[0] = 0
    for i in range(1, amount + 1):
        for coin in coins:
            if coin <= i and memo[i - coin] != sys.maxsize:
                memo[i] = min(memo[i], memo[i - coin] + 1)
    return memo[amount] if memo[amount] != sys.maxsize else -1

The recurrence relation is \(c(i)_{\textrm{best}} = \[ \textrm{min}_{c'} {c(i - c')}_{\textrm{best}} \]\) where \(c(i)\) is the minimum coin change at position \(i\) and \(c'\) represents a given coin out of all the possible coins in coins. Your base case is that there are 0 ways to get an amount of 0 with any given set of coins, as per the example. (Sometimes it makes more sense to say there is 1 way to get that amount - which is to say, do nothing - but for some reason it works here. I’m doing this a bit late at night so I couldn’t tell you why tbh, this does happen though and it comes down to subleties in the problem semantics.)

Once this is figured out, the rest is just coding; I think the only interesting thing is that I initialized all values to some MAX variable to simplify the logic in the for loop; this requires an if-else at the return statement so that you correctly return -1 instead of MAX if a coin cannot be formed. A nice refreshing DP problem.

Leave a comment

Your email address will not be published. Required fields are marked. *

Loading...