I'm attempting the classic coin change problem, my following code works fine, for instance it returns the correct value of 3 with the coin combinations of [1, 2, 5] and a target of 11. However when I add memoization to the recursive calls it comes up with an incorrect answer? What am I doing wrong in the function call?
var coinChange = function(coins, amount, totalCoins = 0, cache = {}) {
if (cache[amount] !== undefined) return cache[amount];
if (amount === 0) {
return totalCoins;
} else if (0 > amount) {
return Number.MAX_SAFE_INTEGER;
} else {
let minCalls = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < coins.length; i++) {
let recursiveCall = coinChange(coins, amount - coins[i], totalCoins + 1, cache);
minCalls = Math.min(minCalls, recursiveCall);
}
const returnVal = (minCalls === Number.MAX_SAFE_INTEGER) ? -1 : minCalls;
return cache[amount] = returnVal;
}
}
console.log(coinChange([1, 2, 5], 11)); // This ends up outputting 7!?!?!