Skip to content

Instantly share code, notes, and snippets.

@kishan-dhankecha
Last active October 13, 2021 09:16
Show Gist options
  • Save kishan-dhankecha/ece39310c1f0b25944a748eaea9ff3f3 to your computer and use it in GitHub Desktop.
Save kishan-dhankecha/ece39310c1f0b25944a748eaea9ff3f3 to your computer and use it in GitHub Desktop.
Best Sum function with memoization [JAVASCRIPT]
/// 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