Maximum possible difference of two subsets of an array | Java find maximum difference of subset sum ; Function for maximum subset diff ; Construct hash for positive elements ; Calculate subset sum for positive elements ; Construct hash for negative elements ; Calculate subset sum for negative elements ; Driver code
import java . util . * ; class GFG { public static int maxDiff ( int arr [ ] , int n ) { HashMap < Integer , Integer > hashPositive = new HashMap < > ( ) ; HashMap < Integer , Integer > hashNegative = new HashMap < > ( ) ; int SubsetSum_1 = 0 , SubsetSum_2 = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] > 0 ) { if ( hashPositive . containsKey ( arr [ i ] ) ) { hashPositive . replace ( arr [ i ] , hashPositive . get ( arr [ i ] ) + 1 ) ; } else { hashPositive . put ( arr [ i ] , 1 ) ; } } } for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] > 0 && hashPositive . containsKey ( arr [ i ] ) ) { if ( hashPositive . get ( arr [ i ] ) == 1 ) { SubsetSum_1 += arr [ i ] ; } } } for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] < 0 ) { if ( hashNegative . containsKey ( Math . abs ( arr [ i ] ) ) ) { hashNegative . replace ( Math . abs ( arr [ i ] ) , hashNegative . get ( Math . abs ( arr [ i ] ) ) + 1 ) ; } else { hashNegative . put ( Math . abs ( arr [ i ] ) , 1 ) ; } } } for ( int i = 0 ; i <= n - 1 ; i ++ ) { if ( arr [ i ] < 0 && hashNegative . containsKey ( Math . abs ( arr [ i ] ) ) ) { if ( hashNegative . get ( Math . abs ( arr [ i ] ) ) == 1 ) { SubsetSum_2 += arr [ i ] ; } } } return Math . abs ( SubsetSum_1 - SubsetSum_2 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 } ; int n = arr . length ; System . out . print ( " Maximum ▁ Difference ▁ = ▁ " + maxDiff ( arr , n ) ) ; } }