Smallest subset of maximum sum possible by splitting array into two subsets | Function to split array elements into two subsets having sum of the smaller subset maximized ; Stores the size of the array ; Stores the frequency of array elements ; Stores the total sum of the array ; Stores the sum of the resultant set ; Stores if it is possible to split the array that satisfies the conditions ; Stores the elements of the first subseta ; Traverse the array arr [ ] ; Increment total sum ; Increment count of arr [ i ] ; Sort the array arr [ ] ; Stores the index of the last element of the array ; Traverse the array arr [ ] ; Stores the frequency of arr [ i ] ; If frq + ans . size ( ) is at most remaining size ; Append arr [ i ] to ans ; Decrement totSum by arr [ i ] ; Increment s by arr [ i ] ; Otherwise , decrement i by frq ; If s is greater than totSum ; Mark flag 1 ; If flag is equal to 1 ; Print the arrList ans ; Otherwise , print " - 1" ; Driver Code
function findSubset ( arr ) { var N = arr . length ; var mp = new Map ( ) ; var totSum = 0 ; var s = 0 ; var flag = 0 ; var ans = [ ] ; for ( var i = 0 ; i < arr . length ; i ++ ) { totSum += arr [ i ] ; if ( mp . has ( arr [ i ] ) ) mp . set ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) else mp . set ( arr [ i ] , 1 ) ; } arr . sort ( ( a , b ) => a - b ) var i = N - 1 ; while ( i >= 0 ) { var frq = mp . get ( arr [ i ] ) ; if ( ( frq + ans . length ) < ( N - ( frq + ans . length ) ) ) { for ( var k = 0 ; k < frq ; k ++ ) { ans . push ( arr [ i ] ) ; totSum -= arr [ i ] ; s += arr [ i ] ; i -- ; } } else { i -= frq ; } if ( s > totSum ) { flag = 1 ; break ; } } if ( flag == 1 ) { for ( i = ans . length - 1 ; i >= 0 ; i -- ) { document . write ( ans [ i ] + " " ) ; } } else { document . write ( - 1 ) ; } } var arr = [ 5 , 3 , 2 , 4 , 1 , 2 ] ; findSubset ( arr ) ;