Skip to content
DSA Patterns
Menu
Language
Knapsack & Subset DPLC #4943 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Target Sum

Problem (restated)

Assign + or - to each nums[i]. Count ways the signed sum equals target.

Intuition

Partition into positive set P and negative set N: P-N=target, P+N=sum ⇒ P=(sum+target)/2. Count subsets summing to P.

Approaches

Subset-sum count reduction

Unverified
Time O(n·Σ)Space O(Σ)

Idea. If sum+target odd or |target|>sum → 0. 0/1 knapsack counting combinations.

Walkthrough. [1,1,1,1,1], target=3 → 5 ways.

Trade-offs. DFS with memo on (i, sum) also works; knapsack is O(nΣ).

Solution
export function findTargetSumWays(nums: number[], target: number): number {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total < Math.abs(target) || (total + target) % 2 !== 0) return 0;
  const need = (total + target) / 2;
  const dp = Array(need + 1).fill(0);
  dp[0] = 1;
  for (const x of nums) {
    for (let c = need; c >= x; c--) dp[c] += dp[c - x]!;
  }
  return dp[need]!;
}
export function findTargetSumWays(nums: number[], target: number): number {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total < Math.abs(target) || (total + target) % 2 !== 0) return 0;
  const need = (total + target) / 2;
  const dp = Array(need + 1).fill(0);
  dp[0] = 1;
  for (const x of nums) {
    for (let c = need; c >= x; c--) dp[c] += dp[c - x]!;
  }
  return dp[need]!;
}

Template connection

need = (sum + target) / 2. An odd sum + target, or |target| > sum, returns 0. Count subsets summing to need with a downward 0/1 knapsack and dp[0] = 1.

Reflection

  • sum(P) - sum(N) = target and the total is fixed, so 2 * sum(P) = total + target. Count the subsets that make that sum(P).
  • If total + target is odd, or the target lies outside the reachable range, the answer is 0. dp[0] = 1.
  • A zero accepts either sign and produces the same sum twice. The question is the assignment of signs, not the order of numbers.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Target sum: assign ± to [1,1,1,1,1] so the signed total is 3.

1
0
1
1
1
2
1
3
1
4

P − N = 3 · P+N = 5

Key:CurrentActive rangeMatchSettledEliminated