◀ THE GRIND — 2-D DYNAMIC PROGRAMMING

Target Sum

MEDIUM✓ CHIP-TIMEDLC #494 — FULL STATEMENT ↗

The drill: Each number in the array gets a + or − sign written in front of it. Count how many different sign assignments make the resulting expression evaluate to the target.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An array of non-negative numbers and a target arrive together. The task is to place either a plus sign or a minus sign in front of every single number, then count how many of those sign assignments make the resulting sum equal the target exactly.

Every number in the array gets exactly one sign — none are skipped and none get both. Two assignments count as different the moment any single number's sign differs between them, even if the totals happen to coincide along the way.

The output is just that count of valid sign assignments, which can be zero if no combination of signs ever lands on the target.

EX 01
nums = [5] · target = 5
1
SINGLE NUMBER, ONLY +5 WORKS
EX 02
nums = [5] · target = -5
1
SINGLE NUMBER, ONLY -5 WORKS
EX 03
nums = [5] · target = 3
0
TARGET UNREACHABLE FROM A SINGLE 5
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Trying every ± assignment is 2^n work, but many assignments end up re-deriving the exact same running total. What repeats across branches?

HINT 2 THE STRUCTURE

Split the numbers into a 'plus' group P and a 'minus' group N. Their difference must equal target, and P + N is always the fixed total of all numbers — so P's required sum is forced the moment you know the total and target.

HINT 3 ONE STEP FROM THE ANSWER

Solve P = (total + target) / 2, then count subsets of nums that sum to exactly P with a reachability-count DP over achievable sums. If P isn't a whole number in range, the answer is zero.

COACH'S BOARD — THE PATTERN, STEP BY STEP
SIGNS AS A SPLITPATTERN · SUBSET SUM — SIGN FLIPPEDnums = [1, 2, 3] · target = 2
1
0
0
0
0
STEP 1

nums=[1,2,3], target=2. total=6, so S=(6+2)/2=4 — count subsets summing to 4; that count is the answer. dp[0]=1.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/target-sum.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        total = sum(nums)
        if abs(target) > total or (total + target) % 2 != 0:
            return 0
        s = (total + target) // 2
        dp = [0] * (s + 1)
        dp[0] = 1
        for x in nums:
            for a in range(s, x - 1, -1):
                dp[a] += dp[a - x]
        return dp[s]
TIME O(N · SUM)SPACE O(SUM)PYTHON · RACE PACE · 12 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED