CodeArchon

medium2-D Dynamic ProgrammingFacebookGoogle

Signed-Sum Picker

A kid assigns + or - to each marble in a bag; count the ways the result equals the target.

Given an integer array and a target, count how many ways to put '+' or '-' signs before each element so that the signed sum equals target.

Choose approach

1
?
?
?
?
1
1
0
0
0
row
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
1/6
Narrationstep 1 of 6

Include/exclude 1; row 1 filled.

1def findTargetSumWays(nums, target):
2 s = sum(nums)
3 if abs(target) > s or (s + target) % 2: return 0
4 S = (s + target) // 2
5 dp = [0]*(S+1); dp[0] = 1
6 for n in nums:
7 for a in range(S, n - 1, -1):
8 dp[a] += dp[a - n]
9 return dp[S]
Variables
using=1
i=1

How to think about it

  1. (sum + target) must be even and non-negative.
  2. Classic subset-sum count.

Edge cases to catch in interview

  • |target| > sum -> 0.
  • Zero in nums doubles ways.

Examples

Example 11
{"nums":[1],"target":1}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed