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
def findMaxSum ( arr , n ) : NEW_LINE INDENT a = [ ] NEW_LINE b = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT a . append ( arr [ i ] ) NEW_LINE DEDENT elif ( arr [ i ] < 0 ) : NEW_LINE INDENT b . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE p = len ( a ) - 1 NEW_LINE q = len ( b ) - 1 NEW_LINE s = 0 NEW_LINE while ( p >= 0 and q >= 0 ) : NEW_LINE INDENT if ( a [ p ] + b [ q ] > 0 ) : NEW_LINE INDENT s = s + a [ p ] + b [ q ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT p = p - 1 NEW_LINE q = q - 1 NEW_LINE DEDENT return s NEW_LINE DEDENT arr1 = [ 1 , - 2 , 3 , 4 , - 5 , 8 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( findMaxSum ( arr1 , n1 ) ) NEW_LINE