Maximum sum subset having equal number of positive and negative elements | C # 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
using System ; using System . Collections . Generic ; class GFG { static int findMaxSum ( int [ ] arr , int n ) { List < int > a = new List < int > ( ) ; List < int > b = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { a . Add ( arr [ i ] ) ; } else if ( arr [ i ] < 0 ) { b . Add ( arr [ i ] ) ; } } a . Sort ( ) ; b . Sort ( ) ; int p = a . Count - 1 ; int q = b . Count - 1 ; int 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 ; } public static void Main ( String [ ] args ) { int [ ] arr1 = { 1 , - 2 , 3 , 4 , - 5 , 8 } ; int n1 = arr1 . Length ; Console . Write ( findMaxSum ( arr1 , n1 ) + " STRNEWLINE " ) ; } }