text: Count ways to split array into two subsets having difference between their sum equal to K | 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 int t [ n + 1 ] [ sum + 1 ] ; ; 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 ; Given Input ; Function Call
code: function countSubset ( arr , n , diff ) { var sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } sum += diff ; sum = sum / 2 ; var t = new Array ( n + 1 ) ; for ( var i = 0 ; i < t . length ; i ++ ) { t [ i ] = new Array ( sum + 1 ) ; } for ( var i = 0 ; i < t . length ; i ++ ) { for ( var j = 0 ; j < t [ i ] . length ; j ++ ) { t [ i ] [ j ] = 0 ; } } for ( var j = 0 ; j <= sum ; j ++ ) t [ 0 ] [ j ] = 0 ; for ( var i = 0 ; i <= n ; i ++ ) t [ i ] [ 0 ] = 1 ; for ( var i = 1 ; i <= n ; i ++ ) { for ( var 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 ] ; } var diff = 1 ; var n = 4 ; var arr = [ 1 , 1 , 2 , 3 ] ; document . write ( countSubset ( arr , n , diff ) ) ;