1
+ package DynamicProgramming .CountOfSubsetsWithAGivenDifference ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ /**
6
+ * * Count of Subsets With A Given Difference (Variation of 0/1 Knapsack)
7
+ */
8
+
9
+ public class Solution {
10
+ public int countOfSubsets (int [] array , int difference ) {
11
+ int sum = Arrays .stream (array ).sum ();
12
+
13
+ return countOfSubsetsDP (array , sum , difference );
14
+ }
15
+
16
+ /**
17
+ * * Dynamic Programming Approach
18
+ *
19
+ * * TC: O(ns)
20
+ * * SC: O(ns)
21
+ */
22
+ private int countOfSubsetsDP (int [] array , int sum , int difference ) {
23
+ /**
24
+ * Equation I: S1 - S2 = difference
25
+ * Equation II: S1 + S2 = sum(array)
26
+ *
27
+ * Adding I and II,
28
+ *
29
+ * 2S1 = sum(array) + difference
30
+ * so, S1 = (sum(array) + difference) / 2
31
+ *
32
+ * Now, we need to find the count of
33
+ * subsets equal to a given sum, which
34
+ * is S1
35
+ */
36
+ int target = (sum + difference ) / 2 ;
37
+
38
+ return countOfSubsetsDP (array , target );
39
+ }
40
+
41
+ private int countOfSubsetsDP (int [] array , int sum ) {
42
+ int len = array .length ;
43
+ int [][] dp = new int [len + 1 ][sum + 1 ];
44
+
45
+ for (int i = 0 ; i < len + 1 ; i ++) dp [i ][0 ] = 1 ;
46
+
47
+ for (int j = 1 ; j < sum + 1 ; j ++) dp [0 ][j ] = 0 ;
48
+
49
+ for (int i = 1 ; i < len + 1 ; i ++) {
50
+ for (int j = 1 ; j < sum + 1 ; j ++) {
51
+ // If the current item is less than
52
+ // or equal to the current sum, then we
53
+ // need to consider both the scenarios
54
+ // where we include this current item and
55
+ // where we don't include this current item
56
+ if (array [i - 1 ] <= j ) dp [i ][j ] = dp [i - 1 ][j ] + dp [i - 1 ][j - array [i - 1 ]];
57
+
58
+ // If the current item is greater
59
+ // than our current sum, then there's
60
+ // only one scenario where we don't
61
+ // include this current item
62
+ else dp [i ][j ] = dp [i - 1 ][j ];
63
+ }
64
+ }
65
+
66
+ return dp [len ][sum ];
67
+ }
68
+
69
+ public static void main (String [] args ) {
70
+ Solution solution = new Solution ();
71
+
72
+ System .out .println (solution .countOfSubsets (new int [] {1 , 1 , 2 , 3 }, 1 ));
73
+ }
74
+ }
0 commit comments