makebetterchange
unknown
javascript
3 years ago
916 B
7
Indexable
function makeBetterChange(target, coins = [25, 10, 5, 1], cache={}) { // Don't need any coins to make 0 cents change if(target in cache) return cache[target]; if (target === 0) return []; //if less than 0, return null for coin, catch null case below if (target < 0) return null; let best_result = null; for (let i = 0; i < coins.length; i++) { const coin = coins[i]; const next_target = target - coin; let sub_result = makeBetterChange(next_target, coins, cache); //only if current coin doesn't give us a NULL value then check if the current combination is the smallest. Else continue. if(sub_result!==null && (best_result === null || (sub_result.length < best_result.length))){ best_result = [coin].concat(sub_result); } } //cache the result so we don't have to evaluate repeats cache[target] = best_result; return best_result }
Editor is loading...