- Arrays, Dynamic Programming, Mathematical, partition, subset

Count ways to split array into two subsets having difference between their sum equal to K

Count ways to split array into two subsets having difference between their sum equal to KGiven an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff.Examples:Input: A[] = {1, 1, 2, 3}, diff = 1  Output: 3  Explanation: All possible combinations are as follows: {1, 1, 2} and {3}{1, 3} and {1, 2}{1, 2} and {1, 3}All partitions have difference between their sums equal to 1. Therefore, the count of ways is 3.Input: A[] = {1, 6, 11, 5}, diff=1Output: 2Naive Approach: The simplest approach to solve the problem is based on the following observations:Let the sum of elements in the partition subsets S1 and S2 be sum1 and sum2 respectively.Let sum of the array A[] be X. Given, sum1 – sum2 = diff – (1)Also, sum1 + sum2 = X – (2)From equations (1) and (2), sum1 = (X + diff)/2Therefore, the task is reduced to finding the number of subsets with a given sum. Therefore, the simplest approach is to solve this problem is by generating all the possible subsets and checking whether the subset has the required sum. Time Complexity: O(2N)Auxiliary Space: O(N)Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Initialize a dp[][] table of size N*X, where dp[i][C] stores the number of subsets of the sub-array A[i…N-1] such that their sum is equal to C. Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t. So the recurrence relation will be:dp[i][C] = dp[i – 1][C – A[i]] + dp[i-1][C]Below is the implementation of the above approach:C++#include using namespace std;int countSubset(int arr[], int n, int diff){        int sum = 0;    for (int i = 0; i < n; i++)        sum += arr[i];    sum += diff;    sum = sum / 2;        int t[n + 1][sum + 1];            for (int j = 0; j