text: Count ways to split array into two subsets having difference between their sum equal to K | Java program for the above approach ; Function to count the number of ways to divide the array into two subsets and such that the difference between their sums is equal to diff ; Store the sum of the set S1 ; Initializing the matrix ; Number of ways to get sum using 0 elements is 0 ; Number of ways to get sum 0 using i elements is 1 ; Traverse the 2D array ; If the value is greater than the sum store the value of previous state ; Return the result ; Driver Code ; Given Input ; Function Call
code: import java . io . * ; public class GFG { static 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 [ ] [ ] = new int [ n + 1 ] [ sum + 1 ] ; for ( int j = 0 ; j <= sum ; j ++ ) t [ 0 ] [ j ] = 0 ; for ( int i = 0 ; i <= n ; i ++ ) t [ i ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( arr [ i - 1 ] > j ) t [ i ] [ j ] = t [ i - 1 ] [ j ] ; else { t [ i ] [ j ] = t [ i - 1 ] [ j ] + t [ i - 1 ] [ j - arr [ i - 1 ] ] ; } } } return t [ n ] [ sum ] ; } public static void main ( String [ ] args ) { int diff = 1 , n = 4 ; int arr [ ] = { 1 , 1 , 2 , 3 } ; System . out . print ( countSubset ( arr , n , diff ) ) ; } }