Last active
February 6, 2021 00:42
-
-
Save Debdut/0d3202840f8d8f078dd23d5b8e8bc602 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function makeChange(x, coinSet) { | |
const mem = [] | |
const getChangeCoins = (value) => { | |
if (!value) { | |
return [] | |
} | |
if (mem[value]) { | |
return mem[value] | |
} | |
let change = [] | |
let newChange | |
let residue | |
for (let i = 0; i < coinSet.length; i++) { | |
const coin = coinSet[i] | |
residue = value - coin | |
if (residue >= 0) { | |
newChange = getChangeCoins(residue) | |
} | |
if (residue >= 0 | |
&& (newChange.length < change.length - 1 || !change.length) | |
&& (newChange.length || !residue)) { | |
change = [coin].concat(newChange) | |
} | |
} | |
mem[value] = change | |
return change | |
} | |
const changeCoins = getChangeCoins(x) | |
if (changeCoins.length === 0) { | |
throw new Error('Change Not Possible') | |
} | |
const change = {} | |
for (let i = 0; i < changeCoins.length; i++) { | |
const coin = changeCoins[i] | |
if (!change[coin]) { | |
change[coin] = 1 | |
} else { | |
change[coin] += 1 | |
} | |
} | |
return change | |
} | |
console.log(makeChange(8, [2,5,10,25])) | |
console.log(makeChange(6, [1,5,10,25])) | |
console.log(makeChange(6, [3,4])) | |
console.log(makeChange(6, [1,3,4])) | |
console.log(makeChange(6, [5,7])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment