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
def SmallestElementLeft ( arr , N ) : NEW_LINE INDENT totalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT req = totalSum // 2 NEW_LINE dp = [ False for i in range ( req + 1 ) ] NEW_LINE memset ( dp , false , sizeof ( dp ) ) ; NEW_LINE dp [ 0 ] = True NEW_LINE reach = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT j = req NEW_LINE while j >= arr [ i ] : NEW_LINE INDENT dp [ j ] = dp [ j ] or dp [ j - arr [ i ] ] NEW_LINE if ( dp [ j ] ) : NEW_LINE INDENT reach = max ( reach , j ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT DEDENT return totalSum - ( 2 * reach ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( SmallestElementLeft ( arr , N ) ) NEW_LINE DEDENT