mediumDynamic ProgrammingDynamic Programming

Target Sum

mediumTime: O(n * sum)Space: O(sum)

Signals to notice

count ways to assign +/- to reach target sumeach number must be usedsubset sum with a twist

Brute force first

Try all 2^n sign assignments. Each number is either + or. giving binary choices. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Transform: find a subset P where sum(P) = (totalSum + target) / 2. This reduces to subset sum counting. dp[j] += dp[j - num] for each number. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

If positive numbers sum to P and negatives to N, then P - N = target and P + N = totalSum. So P = (totalSum + target) / 2. Counting subsets with this sum counts the valid assignments. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not seeing the reduction to subset sum — the +/- assignment can be split into a positive set and negative set, transforming the problem algebraically. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Dynamic Programming Pattern