Maximum possible difference of two subsets of an array | C # find maximum difference of subset sum ; 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
using System ; using System . Collections . Generic ; class GFG { static int maxDiff ( int [ ] arr , int n ) { Dictionary < int , int > hashPositive = new Dictionary < int , int > ( ) ; Dictionary < int , int > hashNegative = new Dictionary < int , int > ( ) ; int SubsetSum_1 = 0 , SubsetSum_2 = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] > 0 ) { if ( hashPositive . ContainsKey ( arr [ i ] ) ) { hashPositive [ arr [ i ] ] += 1 ; } else { hashPositive . Add ( arr [ i ] , 1 ) ; } } } for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] > 0 && hashPositive . ContainsKey ( arr [ i ] ) ) { if ( hashPositive [ arr [ i ] ] == 1 ) { SubsetSum_1 += arr [ i ] ; } } } for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] < 0 ) { if ( hashNegative . ContainsKey ( Math . Abs ( arr [ i ] ) ) ) { hashNegative [ Math . Abs ( arr [ i ] ) ] += 1 ; } else { hashNegative . Add ( Math . Abs ( arr [ i ] ) , 1 ) ; } } } for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] < 0 && hashNegative . ContainsKey ( Math . Abs ( arr [ i ] ) ) ) { if ( hashNegative [ Math . Abs ( arr [ i ] ) ] == 1 ) { SubsetSum_2 += arr [ i ] ; } } } return Math . Abs ( SubsetSum_1 - SubsetSum_2 ) ; } static void Main ( ) { int [ ] arr = { 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 } ; int n = arr . Length ; Console . WriteLine ( " Maximum ▁ Difference ▁ = ▁ " + maxDiff ( arr , n ) ) ; } }