Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

​

Solution: Problem Challenge 2: Target Sum

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 4 years ago

This method cannot past the test case [0,0,0,0,0,0,0,0,1] S = 1 . Is there another solution?

Show 2 replies
A

Anonymous

· 4 years ago

Can you share the Target Sum solution with memoization?

A

Anonymous

· 5 years ago

This is the wrong solution to the problem. The right solution is below,

public int findTargetSumWays(int[] nums, int S) { int total = Arrays.stream(nums).sum(); int[] dp = new int[2 * total + 1]; dp[nums[0] + total] = 1; dp[-nums[0] + total] += 1;

for (int i = 1; i < nums.length; i++) { int[] next = new int[2 * total + 1]; for (int sum = -total; sum 0) { next[sum + nums[i] + total] += dp[sum + total]; next[sum - nums[i] + total] += dp[sum + total]; } } dp = next; }

return Math.abs(S) > total ? 0 : dp[S + total]; }

Show 1 reply

Reading Progress

0%


Vote for new content