Skip to content

Commit 0313c3b

Browse files
Create PartitionsWithGivenDifference.java
1 parent 0b18e5d commit 0313c3b

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.* ;
2+
import java.io.*;
3+
public class PartitionsWithGivenDifference {
4+
public static int countPartitions(int n, int d, int[] arr) {
5+
int mod = 1000000007;
6+
7+
int totalSum = 0;
8+
9+
for(int i = 0; i<n; i++){
10+
totalSum += arr[i];
11+
}
12+
13+
if((totalSum+d) % 2 != 0){
14+
return 0;
15+
}
16+
17+
int s1 = (totalSum+d)/2;
18+
19+
int[][] dp = new int[n][s1+1];
20+
21+
for(int i = 0; i<n; i++){
22+
dp[i][0] = 1;
23+
}
24+
25+
if(arr[0] == 0){
26+
dp[0][0] = 2;
27+
}
28+
29+
if (arr[0] != 0 && arr[0] <= s1) {
30+
dp[0][arr[0]] = 1;
31+
}
32+
33+
for(int i = 1; i<n; i++){
34+
for(int j = 0; j<s1+1; j++){
35+
int notPick = dp[i-1][j];
36+
int pick = 0;
37+
if(j>=arr[i]){
38+
pick = dp[i-1][j-arr[i]];
39+
}
40+
41+
dp[i][j] = (pick + notPick)%mod;
42+
}
43+
}
44+
return dp[n-1][s1];
45+
}
46+
}

0 commit comments

Comments
 (0)