DEV Community

Cover image for Coin change problem
Nantipat
Nantipat

Posted on

3 2

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay