-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPartitionsWithGivenSum.java
More file actions
35 lines (28 loc) · 906 Bytes
/
PartitionsWithGivenSum.java
File metadata and controls
35 lines (28 loc) · 906 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package dp.knapsack01;
/**
* Can we partition such that the two arrays have difference equal to d
*/
public class PartitionsWithGivenSum {
static int mod = 1000000007;
public static int countPartitions(int n, int d, int[] arr) {
int sum = 0;
for (int i = 0; i < n; i++) sum += arr[i];
sum += d;
if (sum % 2 != 0) return 0;
sum /= 2;
int[][] t = new int[n + 1][sum + 1];
for (int i = 0; i <= n; i++) t[i][0] = 1;
for (int i = 1; i <= sum; i++) t[0][i] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (arr[i - 1] <= j) {
t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]];
} else {
t[i][j] = t[i - 1][j];
}
t[i][j] %= mod;
}
}
return t[n][sum];
}
}