Last active
October 20, 2023 01:55
-
-
Save alvinlau/ded4d88d57e4997b00435d514aecac2a to your computer and use it in GitHub Desktop.
322. Coin Change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://leetcode.com/problems/coin-change/description/ | |
| # 322. Coin Change | |
| # 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 | |
| # @param {Integer[]} coins | |
| # @param {Integer} amount | |
| # @return {Integer} | |
| def coin_change(coins, amount) | |
| return 0 if amount == 0 | |
| pick_coin(coins.sort.reverse, amount, {}) | |
| end | |
| def pick_coin(coins, amount, cache) | |
| valid_coins = coins.select{|coin| coin <= amount} | |
| return -1 if valid_coins.empty? # deadend | |
| return 1 if valid_coins.any?{|coin| coin == amount} # trivial | |
| return cache[amount] if cache[amount] | |
| results = valid_coins.map do |coin| | |
| next cache[amount-coin]+1 if cache[amount-coin] | |
| 1 + pick_coin(coins, amount - coin, cache) | |
| end | |
| valid_results = results.select{|result| result > 0} | |
| result = valid_results.empty? ? -1 : valid_results.min | |
| cache[amount] ||= result | |
| cache[amount] = result if result < cache[amount] | |
| return result | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment