Minimize remaining array element by removing pairs and replacing them by their absolute difference | Function to find minimize the remaining array element by removing pairs and replacing them by their absolute difference ; Stores sum of array elements ; Traverse the array ; Update totalSum ; Stores half of totalSum ; dp [ i ] : True if sum i can be obtained as a subset sum ; Base case ; Stores closest sum that can be obtained as a subset sum ; Traverse the array ; Iterate over all possible value of sum ; Update dp [ j ] ; If sum i can be obtained from array elements ; Update reach ; Driver Code
function SmallestElementLeft ( arr , N ) { var totalSum = 0 ; for ( i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } var req = totalSum / 2 ; var dp = Array ( req + 1 ) . fill ( false ) ; dp [ 0 ] = true ; var reach = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = req ; j - arr [ i ] >= 0 ; j -- ) { dp [ j ] = dp [ j ] || dp [ j - arr [ i ] ] ; if ( dp [ j ] ) { reach = Math . max ( reach , j ) ; } } } return totalSum - ( 2 * reach ) ; } var arr = [ 2 , 2 , 2 ] ; var N = arr . length ; document . write ( SmallestElementLeft ( arr , N ) ) ;