2

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!?!?!
Afs35mm
  • 549
  • 2
  • 8
  • 21

1 Answers1

0

You should not pass totalCoins as function argument for recursive call because that's what you are trying to calculate. Instead it should be calculated as follows

var coinChange = function(coins, amount, cache = {}) {
    if (cache[amount] !== undefined) return cache[amount];
    if (amount === 0) {
        return 0;
    } 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 = 1 + coinChange(coins, amount - coins[i], 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 outputs 3

Note this line

let recursiveCall = 1 + coinChange(coins, amount - coins[i], cache);
xashru
  • 3,400
  • 2
  • 17
  • 30