Maximum sum subset having equal number of positive and negative elements | Function to find maximum sum subset with equal number of positive and negative elements ; Loop to store the positive and negative elements in two different array ; Sort both the array ; Pointers starting from the highest elements ; Find pairs having sum greater than zero ; Driver code
function findMaxSum ( arr , n ) { var a = [ ] ; var b = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { a . push ( arr [ i ] ) ; } else if ( arr [ i ] < 0 ) { b . push ( arr [ i ] ) ; } } a . sort ( ( a , b ) => a - b ) b . sort ( ( a , b ) => a - b ) var p = a . length - 1 ; var q = b . length - 1 ; var s = 0 ; while ( p >= 0 && q >= 0 ) { if ( a [ p ] + b [ q ] > 0 ) { s = s + a [ p ] + b [ q ] ; } else { break ; } p = p - 1 ; q = q - 1 ; } return s ; } var arr1 = [ 1 , - 2 , 3 , 4 , - 5 , 8 ] ; var n1 = arr1 . length ; document . write ( findMaxSum ( arr1 , n1 ) ) ;