Source: https://leetcode.com/problems/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.

/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
// Top Down Recursive Approach with Memoization
// O(N*C) time where N is the total amount, C is the total number of different coins
// O(N) space to hold amount keys in the memo + the recursive stack space
var coinChange = function(coins, amount) {
if (amount === 0) {
return 0;
}
const memo = {};
const coinChangeHelper = (currentAmount) => {
if (memo.hasOwnProperty(currentAmount)) {
return memo[currentAmount];
}
if (currentAmount === 0) {
return 0;
}
if (currentAmount < 0) {
return Infinity;
}
let minCoins = Infinity;
coins.forEach((coin) => {
let currentMinCoins = coinChangeHelper(currentAmount - coin);
if (currentMinCoins >= 0 && currentMinCoins !== Infinity) {
currentMinCoins += 1;
}
minCoins = Math.min(currentMinCoins, minCoins);
});
memo[currentAmount] = minCoins;
return minCoins;
};
const result = coinChangeHelper(amount);
return result === Infinity ? -1 : result;
};