Skip to content
Advertisement

Why does howSum solution work in Javascript but not in Python? (Dynamic programming)

This is a follow-up to this question asked on Stack Overflow.

Write a function ‘howSum(targetSum, numbers)’ that takes in a targetSum and an array of numbers as arguments.

The function should return an array containing any combination of elements that add up to exactly the targetSum.

If there is no combination that adds up to the targetSum, then return None. If there are multiple combinations possible, you may return any single one.

My memoized python code for the solution is as follows:

JavaScript

The algorithm works but not as efficiently for the final test case. In fact, the runtime efficiency is no different than the brute force solution. What’s the problem?

Advertisement

Answer

You don’t seem to pass the memo value to the recursive howSum(remainder, nums) call, so you’re losing the benefit of memoizing there.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement