Practice › Dynamic Programming
Target Sum
Medium · Dynamic Programming · Asked at Meta, Amazon, Google, Microsoft
Put a + or a − sign in front of every number of the array. Count the ways to make the resulting expression equal target, and print the count modulo 10^9 + 7.
Input
First line: n. Second line: n space-separated integers. Third line: target.
Output
The number of ways modulo 10^9 + 7.
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ a[i] ≤ 1000
- sum of a ≤ 10^4
- |target| ≤ 10^4
If P is the sum of the numbers with +, then P − (S − P) = target, so P = (S + target) / 2. Count the subsets with sum P (a 0/1-knapsack count); if S + target is odd or negative, the answer is 0. Zeros double the count, which the subset DP handles on its own.
Example 1
Input
5 1 1 1 1 1 3
Output
5
Example 2
Input
1 1 1
Output
1
Hints
- Split the numbers into a plus-group P and a minus-group.
- P − (S − P) = target, so P = (S + target) / 2.
- Now count subsets with sum P — a 0/1 knapsack count.
Approach
Let S be the total. If S + target is odd, negative, or |target| > S, no assignment works — print 0. Otherwise count subsets summing to P = (S + target) / 2 with dp[v] = number of ways to reach sum v, iterating v downwards for each number so it is used at most once. A 0 adds dp[v] to itself, doubling the count, exactly matching its two possible signs.
Complexity: O(n · P) time · O(P) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
const long long MOD = 1000000007LL;
int n;
cin >> n;
vector<int> a(n);
long long S = 0;
for (auto &x : a) {
cin >> x;
S += x;
}
long long target;
cin >> target;
if ((S + target) % 2 != 0 || S + target < 0 || llabs(target) > S) {
cout << 0 << "\n";
return 0;
}
int P = (S + target) / 2;
vector<long long> dp(P + 1, 0);
dp[0] = 1;
for (int x : a)
for (int v = P; v >= x; v--) dp[v] = (dp[v] + dp[v - x]) % MOD;
cout << dp[P] << "\n";
return 0;
}Python solution
import sys
MOD = 10**9 + 7
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
target = data[1 + n]
S = sum(a)
if (S + target) % 2 or S + target < 0 or abs(target) > S:
print(0)
else:
P = (S + target) // 2
dp = [0] * (P + 1)
dp[0] = 1
for x in a:
for v in range(P, x - 1, -1):
dp[v] = (dp[v] + dp[v - x]) % MOD
print(dp[P])Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
final long MOD = 1000000007L;
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int[] a = new int[n];
long S = 0;
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (int) in.nval;
S += a[i];
}
in.nextToken();
long target = (long) in.nval;
if ((S + target) % 2 != 0 || S + target < 0 || Math.abs(target) > S) {
System.out.println(0);
return;
}
int P = (int) ((S + target) / 2);
long[] dp = new long[P + 1];
dp[0] = 1;
for (int x : a)
for (int v = P; v >= x; v--) dp[v] = (dp[v] + dp[v - x]) % MOD;
System.out.println(dp[P]);
}
}