Maximum possible difference of sum of two subsets of an array | Set 2 | package whatever do not write package name here ; 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
import java . io . * ; import java . util . * ; class GFG { static int maxSumAfterPartition ( int arr [ ] , int n ) { ArrayList < Integer > pos = new ArrayList < Integer > ( ) ; ArrayList < Integer > neg = new ArrayList < Integer > ( ) ; int zero = 0 ; int pos_sum = 0 ; int neg_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { pos . add ( arr [ i ] ) ; pos_sum += arr [ i ] ; } else if ( arr [ i ] < 0 ) { neg . add ( arr [ i ] ) ; neg_sum += arr [ i ] ; } else { zero ++ ; } } int ans = 0 ; Collections . sort ( pos ) ; Collections . sort ( neg ) ; if ( pos . size ( ) > 0 && neg . size ( ) > 0 ) { ans = ( pos_sum - neg_sum ) ; } else if ( pos . size ( ) > 0 ) { if ( zero > 0 ) { ans = ( pos_sum ) ; } else { ans = ( pos_sum - 2 * pos . get ( 0 ) ) ; } } else { if ( zero > 0 ) { ans = ( - 1 * neg_sum ) ; } else { ans = ( neg . get ( 0 ) - ( neg_sum - neg . get ( 0 ) ) ) ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , - 5 , - 7 } ; int n = 5 ; System . out . println ( maxSumAfterPartition ( arr , n ) ) ; } }