Last active
October 13, 2021 09:16
-
-
Save kishan-dhankecha/ece39310c1f0b25944a748eaea9ff3f3 to your computer and use it in GitHub Desktop.
Best Sum function with memoization [JAVASCRIPT]
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
/// Write a function 'bestSum(targetSum, numbers)' that takes in a | |
/// targetSum and an array of numbers as arguments. | |
/// The function should return an array containing the shortest | |
/// combination of numbers that add up to exactly the targetSum. | |
/// If there is a tie for the shortest combination, you may return any | |
/// one of the shortest. | |
const bestSum = (targetSum, numbers, memory = {}) => { | |
// Check in memory. | |
if (targetSum in memory) return memory[targetSum]; | |
// Return obvious values to stop recursion. | |
if (targetSum === 0) return []; | |
if (targetSum < 0) return null; | |
let shortestCombination = null; | |
// Iterate through numbers array | |
for (let num of numbers) { | |
const remainder = targetSum - num; | |
const remainderCombination = bestSum(remainder, numbers, memory); | |
if (remainderCombination !== null) { | |
const combination = [...remainderCombination, num]; | |
// If the combination is shorter than the current 'shortest', update it. | |
if (shortestCombination === null || combination.length < shortestCombination.length) { | |
shortestCombination = combination; | |
} | |
} | |
} | |
// Return value. | |
memory[targetSum] = shortestCombination; | |
return shortestCombination; | |
} | |
console.log(bestSum(7, [5, 3, 4, 7])); // [7] | |
console.log(bestSum(8, [1, 4, 5])); // [4, 4] | |
console.log(bestSum(100, [1, 2, 5, 25])); // [25, 25, 25, 25] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment