Professional Documents
Culture Documents
Solving The Target Sum Problem With Dynamic Programming and More - by Fabian Terh - The Startup - Medium
Solving The Target Sum Problem With Dynamic Programming and More - by Fabian Terh - The Startup - Medium
int ans =
backtrack(memo, nums, index + 1, sum +
nums[index], s) +
backtrack(memo, nums, index + 1, sum -
nums[index], s);
memo[index][sum + 1000] = ans;
return ans;
}
}
68.82th percentile. Not great, not terrible either.
Solution 3: Dynamic programming
Finally, we turn to the dynamic programming solutions.
At the (rst iteration (i.e. the outer for-loop), assume that we are
on value x in our nums array. Therefore, we know intuitively that
there is only one way to reach the target sum of +x and -x.
(Explanation: you start with 0, and you either +x or -x.)
Programmatically, we can express this logic by setting ways to
reach 0 .
You can also use a HashMap and only iterate through all existing
keys, which is theoretically faster but slower in practice. It is
theoretically more eLcient because you don’t have to iterate
through all 2 * sum + 1 indices in the array at each iteration of
the nums array; however, it seems that the overhead of using the
HashMap data structure far outweighs the cost of performing that
iteration.
83.83th percentile: we’re Hnally getting somewhere!
Therefore…
sum(nums)) / 2 .
class Solution {
public int findTargetSumWays(int[] nums, int S) {
int sum = 0;
for (int num: nums) sum += num;
if (S > sum || -S < -sum || (S + sum) % 2 == 1)
return 0;
Follow
Honestly, this solution took me a while to wrap my head around.
The reformulated problem statement so faintly resembled the
original
338
one that I had trouble convincing myself of the
correctness of the solution (i.e. that solving the reformulated
1
problem solves the original one). I found that the best way to
truly understand the solution is to step through it line-by-line, and
really understanding what each step does.
. . .
This article has been a blast to write, and I think it’s amazing how
we were able to bring our runtime down from 377ms to 1ms by
optimizing our solution. Even just simply caching our solutions
(through memoization) reduced our runtime to 8ms, which is an
extremely signiJcant improvement.
A newsletter that delivers The Startup's most popular stories to your inbox
once a month. Take a look