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 ; 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
def countSubset ( arr , n , diff ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT sum += diff NEW_LINE sum = sum // 2 NEW_LINE t = [ [ 0 for i in range ( sum + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for j in range ( sum + 1 ) : NEW_LINE INDENT t [ 0 ] [ j ] = 0 NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT t [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] > j ) : NEW_LINE INDENT t [ i ] [ j ] = t [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT t [ i ] [ j ] = t [ i - 1 ] [ j ] + t [ i - 1 ] [ j - arr [ i - 1 ] ] NEW_LINE DEDENT DEDENT DEDENT return t [ n ] [ sum ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT diff , n = 1 , 4 NEW_LINE arr = [ 1 , 1 , 2 , 3 ] NEW_LINE print ( countSubset ( arr , n , diff ) ) NEW_LINE DEDENT