Target Sum

Let's solve the Target Sum problem using Dynamic Programming.

Statement

Given an array of positive integers, arr, and a target, T, build an expression using these numbers by inserting a ++ or a - before each integer, and evaluating this expression. Find the total number of different expressions that evaluate to T.

For example, considering an array [1, 1] and a target 0, we can build the following expressions:

Expression

Sum

+ 1 + 1

2

+ 1 – 1

0

– 1 + 1

0

– 1 – 1

–2

The total number of expressions that evaluate to the target is 2.

Constraints:

  • 11 \leq arr.length 40\leq 40

  • 00 \leq arr[i] 1000\leq 1000

  • 00 \leq sum(arr[i]) 1000\leq 1000

  • 1000-1000 \leq T 1000\leq 1000

Examples

No.

arr

T

Number of Expressions

1

[1, 2, 1]

0

2

2

[1, 1, 1, 1]

2

4

Try it yourself

Implement your solution in the following playground.

Press + to interact
Java
usercode > Solution.java
import java.util.stream.*;
import java.util.*;
public class Solution{
public static int findTargetSumWays(int[] arr, int T){
// Write your code here
return -1;
}
}
Target Sum

Note: If you clicked the "Submit" button and the code timed out, this means that your solution needs to be optimized in terms of running time.

Hint: Use dynamic programming and see the magic.

Solution

We will first explore the naive recursive solution to this problem and then see how it can be improved using the 0/1 Knapsack dynamic programming pattern.

Naive approach

A naive approach to this problem is to find all expressions using the given numbers and then count the number of expressions that evaluate to the given target.

For example, we have an array [2, 1, 2], and we can build the following expressions:

  • +2+1+2=5+2+1+2=5
  • +21+2=3+2-1+2=3
...
  • +2+12=1+2+1-2=1
  • +212=1+2-1-2=-1
...
Access this course and 1400+ top-rated courses and projects.