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 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:
arr.length
arr[i]
sum(arr[i])
T
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.
import java.util.stream.*;import java.util.*;public class Solution{public static int findTargetSumWays(int[] arr, int T){// Write your code herereturn -1;}}
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: