-
Notifications
You must be signed in to change notification settings - Fork 1
/
PartitionsWithGivenDifference.java
55 lines (46 loc) · 1.23 KB
/
PartitionsWithGivenDifference.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
static int mod = 1000000007;
public static int countPartitions(int n, int d, int[] arr) {
Arrays.sort(arr);//For when array also contain 0
descending(arr);
int total = 0;
for(int i=0;i<arr.length;i++) {
total += arr[i];
}
int sum = (d+total);
if(sum%2==0){//if sum is odd then it is never possible to partition into 2 subset.
sum = sum/2;
}else{
return 0;
}
int dp[][] = new int[arr.length+1][sum+1];
for(int row[] : dp) {
Arrays.fill(row,-1);
}
int ans = solve(arr,dp,sum,arr.length-1);
return ans;
}
private static int solve(int[] arr,int[][] dp,int sum, int pos) {
if(pos<0) {
return (sum==0)?1:0;
}
if(dp[pos][sum]!=-1) {
return dp[pos][sum];
}
if(arr[pos]>sum) {//exclude
dp[pos][sum] = solve(arr,dp,sum,pos-1);
}else {
dp[pos][sum] = (solve(arr,dp,sum-arr[pos],pos-1)
+
solve(arr, dp, sum, pos-1))%mod;
}
return dp[pos][sum]%mod;
}
public static void descending(int arr[]){
for(int i=0;i<arr.length/2;i++){
int temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
}
}