Minimize remaining array element by removing pairs and replacing them by their absolute difference | javascript program of the above approach ; Function to find the smallest element left in the array by the given operations ; Base Case ; If this subproblem has occurred previously ; Including i - th array element into the first subset ; If i - th array element is not selected ; Update dp [ i ] [ sum ] ; Utility function to find smallest element left in the array by the given operations ; Stores sum of the array elements ; Traverse the array ; Update total ; Stores overlapping subproblems ; Driver Code
let M = 6 ; let N = 7 ; function smallestLeft ( arr , total , sum , i , dp ) { if ( i == 0 ) { return Math . abs ( total - 2 * sum ) ; } if ( dp [ i ] [ sum ] != - 1 ) return dp [ i ] [ sum ] ; let X = smallestLeft ( arr , total , sum + arr [ i - 1 ] , i - 1 , dp ) ; let Y = smallestLeft ( arr , total , sum , i - 1 , dp ) ; return dp [ i ] [ sum ] = Math . min ( X , Y ) ; } function UtilSmallestElement ( arr , N ) { let total = 0 ; for ( let i = 0 ; i < N ; i ++ ) { total += arr [ i ] ; } let dp = new Array ( N + 1 ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( var i = 0 ; i < dp . length ; i ++ ) { for ( var j = 0 ; j < dp . length ; j ++ ) { dp [ i ] [ j ] = 1 ; } } document . write ( smallestLeft ( arr , total , 0 , N , dp ) ) ; } let arr = [ 2 , 7 , 4 , 1 , 8 , 1 ] ; let n = arr . length ; UtilSmallestElement ( arr , n ) ;