Maximum possible difference of two subsets of an array | function for maximum subset diff ; sort the array ; calculate the result ; check for last element ; return result ; driver program
function maxDiff ( arr , n ) { var result = 0 ; arr . sort ( ( a , b ) => a - b ) for ( var i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) result += Math . abs ( arr [ i ] ) ; else i ++ ; } if ( arr [ n - 2 ] != arr [ n - 1 ] ) result += Math . abs ( arr [ n - 1 ] ) ; return result ; } var arr = [ 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 ] ; var n = arr . length ; document . write ( " " + maxDiff ( arr , n ) ) ;