Maximum sum subset having equal number of positive and negative elements | Java implementation to find the maximum sum subset having equal number of positive and negative elements in the subset ; 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
import java . util . * ; class GFG { static int findMaxSum ( int [ ] arr , int n ) { Vector < Integer > a = new Vector < Integer > ( ) ; Vector < Integer > b = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { a . add ( arr [ i ] ) ; } else if ( arr [ i ] < 0 ) { b . add ( arr [ i ] ) ; } } Collections . sort ( a ) ; Collections . sort ( b ) ; int p = a . size ( ) - 1 ; int q = b . size ( ) - 1 ; int s = 0 ; while ( p >= 0 && q >= 0 ) { if ( a . get ( p ) + b . get ( q ) > 0 ) { s = s + a . get ( p ) + b . get ( q ) ; } else { break ; } p = p - 1 ; q = q - 1 ; } return s ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , - 2 , 3 , 4 , - 5 , 8 } ; int n1 = arr1 . length ; System . out . print ( findMaxSum ( arr1 , n1 ) + "NEW_LINE"); } }