Maximum possible difference of sum of two subsets of an array | Set 2 | Python 3 Program for 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
def maxSumAfterPartition ( arr , n ) : NEW_LINE INDENT pos = [ ] NEW_LINE neg = [ ] NEW_LINE zero = 0 NEW_LINE pos_sum = 0 NEW_LINE neg_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos . append ( arr [ i ] ) NEW_LINE pos_sum += arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < 0 ) : NEW_LINE INDENT neg . append ( arr [ i ] ) NEW_LINE neg_sum += arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE pos . sort ( ) NEW_LINE neg . sort ( reverse = True ) NEW_LINE if ( len ( pos ) > 0 and len ( neg ) > 0 ) : NEW_LINE INDENT ans = ( pos_sum - neg_sum ) NEW_LINE DEDENT elif ( len ( pos ) > 0 ) : NEW_LINE INDENT if ( zero > 0 ) : NEW_LINE INDENT ans = ( pos_sum ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( pos_sum - 2 * pos [ 0 ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( zero > 0 ) : NEW_LINE INDENT ans = ( - 1 * neg_sum ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( neg [ 0 ] - ( neg_sum - neg [ 0 ] ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , - 5 , - 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSumAfterPartition ( arr , n ) ) NEW_LINE DEDENT