Created
December 16, 2016 16:33
-
-
Save youssef06/aebdfa9cfb79411eacd1a77b66322675 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
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