InferenceAI

Enter at least two characters to search.

Start free

Signed Target Ways

mediumDynamic Programming25 min25 XP

Put a + or - in front of every number in nums. Return how many assignments make the expression equal target.

Requirements

  • Reduce to subset counting: if PP is the positive subset, sum(P)=target+total2\text{sum}(P) = \frac{\text{target} + \text{total}}{2}.

Examples

EXAMPLE WALKTHROUGHfive ones

A guided view of the published example, not a trace of your code.

INPUT[[1,1,1,1,1],3]
TASKsigned_target_ways()
EXPECTED OUTPUT5

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [1,1,1,1,1], target = 3

Output: 5

Explanation: five ones

Input: nums = [1], target = 1

Output: 1

Explanation: single

Input: nums = [1], target = 2

Output: 0

Explanation: impossible

Hint 1

If (target + total) is odd or negative, the answer is 0.

Hint 2

Count subsets with that sum using a 1D DP over sums.

Topics

DSADynamic ProgrammingPython