Maximum possible difference of two subsets of an array | function for maximum subset diff ; construct hash for positive elements ; calculate subset sum for positive elements ; construct hash for negative elements ; calculate subset sum for negative elements ; Driver Code
def maxDiff ( arr , n ) : NEW_LINE INDENT hashPositive = dict ( ) NEW_LINE hashNegative = dict ( ) NEW_LINE SubsetSum_1 , SubsetSum_2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT hashPositive [ arr [ i ] ] = hashPositive . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 and arr [ i ] in hashPositive . keys ( ) and hashPositive [ arr [ i ] ] == 1 ) : NEW_LINE INDENT SubsetSum_1 += arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT hashNegative [ abs ( arr [ i ] ) ] = hashNegative . get ( abs ( arr [ i ] ) , 0 ) + 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 and abs ( arr [ i ] ) in hashNegative . keys ( ) and hashNegative [ abs ( arr [ i ] ) ] == 1 ) : NEW_LINE INDENT SubsetSum_2 += arr [ i ] NEW_LINE DEDENT DEDENT return abs ( SubsetSum_1 - SubsetSum_2 ) NEW_LINE DEDENT arr = [ 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ Difference ▁ = " , maxDiff ( arr , n ) ) NEW_LINE