DEV Community

Discussion on: Daily Challenge #45 - Change Machine

Collapse
 
jasman7799 profile image
Jarod Smith

Greedy solution in JS

function getChange(n) {
  n = BigInt(n);
  let amount = 0n;
  let coinIndex = 3;
  let change = {
    25: 0n,
    10: 0n,
    5: 0n,
    1: 0n
  }
  const coins = [1n,5n,10n,25n];
  while(amount < n) {
    let divisibilty = ((n - amount) / coins[coinIndex]);
    if (divisibilty >= 1n) {
      change[coins[coinIndex]] += divisibilty;
      amount += (coins[coinIndex] * divisibilty);
    }
    else
      coinIndex--;
  }
  return change;
}