DEV Community

Cover image for Coin change problem
Nantipat
Nantipat

Posted on

Coin change problem

https://www.cs.usfca.edu/~galles/visualization/DPChange.html

const coin_change_bottom_up = (coins, sum) => {
  let memo = new Array(sum + 1).fill(Infinity);
  memo[0] = 0;
  for (let i = 1; i <= sum; i++) {
    for (let coin = 0; coin < coins.length; coin++) {
      if (coins[coin] <= i) {
        memo[i] = Math.min(memo[i], 1 + memo[i - coins[coin]]);
      }
    }
  }
  return memo[sum];
  // O(n*m)
};

let coins = [1, 5, 10, 25];
let sum = 18;
console.log(coin_change_bottom_up(coins, sum));
//---------------------------------

const coin_change_top_dowm = (coins, sum, memo) => {
  if (sum == 0) return 0;
  if (sum < 0) return 1e9; // 1e9 = 1,000,000,000
  // already solved cases:
  let ans = Infinity;

  for (let coin = 0; coin < coins.length; coin++) {
    if (coins[coin] <= sum) {
      let sub_ans = 1 + coin_change_top_dowm(coins, sum - coins[coin], memo);
      //   console.log(sub_ans);

      ans = Math.min(ans, sub_ans);
    }
  }
  memo[sum] = ans;
  return memo[sum];
};

let memo = new Array(sum + 1).fill(Infinity);
console.log(coin_change_top_dowm(coins, sum, memo));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)