Skip to content

Instantly share code, notes, and snippets.

@youssef06
Created December 16, 2016 16:33
Show Gist options
  • Save youssef06/aebdfa9cfb79411eacd1a77b66322675 to your computer and use it in GitHub Desktop.
Save youssef06/aebdfa9cfb79411eacd1a77b66322675 to your computer and use it in GitHub Desktop.
var cache = new Map()
function getCoinsChange(n, coins) {
if(coins.indexOf(n) != -1)
return 1
var cacheKey = JSON.stringify({n, coins})
if(!cache.has(cacheKey))
{
var min_coins = n
for(var i = 0; i < coins.length; i++) {
if(coins[i]>n) continue
var sum = parseInt(n/coins[i])
var rest = n%coins[i]
if(rest>0) {
sum += getCoinsChange(rest, coins)
}
min_coins = Math.min(min_coins, sum)
}
cache.set(cacheKey, min_coins)
return min_coins
} else
return cache.get(cacheKey)
}
assert.deepEqual(getCoinsChange(45, [1,5,10,25]), 3)
assert.deepEqual(getCoinsChange(23, [1,5,10,25]), 5)
assert.deepEqual(getCoinsChange(74, [1,5,10,25]), 8)
assert.deepEqual(getCoinsChange(30, [1,15,25]), 2)
assert.deepEqual(getCoinsChange(63, [1,5,10, 25]), 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment