1) P1_S1 != P2_S1 i.e, at least one of the elements of P1_S1 is different from P2_S2.
2) P1_S1 == P2_S2, but the indices set represented by P1_S1 is not equal to the indices set of P2_S2. Here, the indices set of P1_S1 is formed by taking the indices of the elements from which the subset is formed.
Refer to the example below for clarification.
If N = 4, D = 3, ARR = {5, 2, 5, 1}
There are only two possible partitions of this array.
Partition 1: {5, 2, 1}, {5}. The subset difference between subset sum is: (5 + 2 + 1) - (5) = 3
Partition 2: {5, 2, 1}, {5}. The subset difference between subset sum is: (5 + 2 + 1) - (5) = 3
These two partitions are different because, in the 1st partition, S1 contains 5 from index 0, and in the 2nd partition, S1 contains 5 from index 2.
We can try all possible array subsets and take them as the first subset. The elements not included in this subset will be taken in the second subset. Let ‘S1’, ‘S2’ be the sum of elements of these two subsets. We then check whether the condition S1 - S2 = D is satisfied or not.
If satisfied, increment the count.
The steps are as follows:
Note that we don’t have to create the subset explicitly. We only have to maintain a variable that stores the sum of this subset.
Let the sums of the elements of both the subsets be ‘S1’ and ‘S2’.
Then, S1 + S2 = total_sum (Here, ‘total_sum’ is the sum of all the array elements).
Also, the condition S1 - S2 = D needs to be satisfied.
We get 2 * S1 = total_sum + D when we sum these two equations.
And, if we subtract these two equations, we get 2 * S2 = total_sum - D.
The problem is reduced to finding subsets with subset-sum equal to (total_sum - D) / 2 (let’s say target), which is our standard Knapsack problem, solved by Dynamic Programming.
Let the sums of the elements of both the subsets be ‘S1’ and ‘S2’.
Then, S1 + S2 = total_sum (Here, ‘total_sum’ is the sum of all the array elements).
Also, the condition S1 - S2 = D needs to be satisfied.
We get 2 * S1 = total_sum + D when we sum these two equations.
And, if we subtract these two equations, we get 2 * S2 = total_sum - D.
The problem is reduced to finding subsets with subset-sum equal to (total_sum - D) / 2 (let’s say target), which is our standard Knapsack problem, solved by Dynamic Programming.