Maximum possible difference of sum of two subsets of an array | Set 2 | JavaScript Program to implement the above approach ; Stores the positive elements ; Stores the negative elements ; Stores the count of 0 s ; Sum of all positive numbers ; Sum of all negative numbers ; Iterate over the array ; Stores the difference ; Sort the positive numbers in ascending order ; Sort the negative numbers in decreasing order ; Case 1 : Include both positive and negative numbers ; Put all numbers in subset A and one 0 in subset B ; Put all numbers in subset A except the smallest positive number which is put in B ; Put all numbers in subset B and one 0 in subset A ; Place the largest negative number in subset A and remaining in B ; Driver code
function maxSumAfterPartition ( arr , n ) { let pos = [ ] ; let neg = [ ] ; let zero = 0 ; let pos_sum = 0 ; let neg_sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { pos . push ( arr [ i ] ) ; pos_sum += arr [ i ] ; } else if ( arr [ i ] < 0 ) { neg . push ( arr [ i ] ) ; neg_sum += arr [ i ] ; } else { zero ++ ; } } let ans = 0 ; pos . sort ( function ( a , b ) { return a - b } ) neg . sort ( function ( a , b ) { return b - a } ) if ( pos . length > 0 && neg . length > 0 ) { ans = ( pos_sum - neg_sum ) ; } else if ( pos . length > 0 ) { if ( zero > 0 ) { ans = ( pos_sum ) ; } else { ans = ( pos_sum - 2 * pos [ 0 ] ) ; } } else { if ( zero > 0 ) { ans = ( - 1 * neg_sum ) ; } else { ans = ( neg [ 0 ] - ( neg_sum - neg [ 0 ] ) ) ; } } return ans ; } let arr = [ 1 , 2 , 3 , - 5 , - 7 ] ; let n = arr . length ; document . write ( maxSumAfterPartition ( arr , n ) ) ;