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
function maxDiff ( arr , n ) { let hashPositive = new Map ( ) ; let hashNegative = new Map ( ) ; let SubsetSum_1 = 0 , SubsetSum_2 = 0 ; for ( let i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] > 0 ) { if ( hashPositive . has ( arr [ i ] ) ) { hashPositive . set ( arr [ i ] , hashPositive . get ( arr [ i ] ) + 1 ) ; } else { hashPositive . set ( arr [ i ] , 1 ) ; } } } for ( let i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] > 0 && hashPositive . has ( arr [ i ] ) ) { if ( hashPositive . get ( arr [ i ] ) == 1 ) { SubsetSum_1 += arr [ i ] ; } } } for ( let i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] < 0 ) { if ( hashNegative . has ( Math . abs ( arr [ i ] ) ) ) { hashNegative . set ( Math . abs ( arr [ i ] ) , hashNegative . get ( Math . abs ( arr [ i ] ) ) + 1 ) ; } else { hashNegative . set ( Math . abs ( arr [ i ] ) , 1 ) ; } } } for ( let i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] < 0 && hashNegative . has ( Math . abs ( arr [ i ] ) ) ) { if ( hashNegative . get ( Math . abs ( arr [ i ] ) ) == 1 ) { SubsetSum_2 += arr [ i ] ; } } } return Math . abs ( SubsetSum_1 - SubsetSum_2 ) ; } let arr = [ 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 ] ; let n = arr . length ; document . write ( " " + maxDiff ( arr , n ) ) ;