Array element with minimum sum of absolute differences | Set 2 | Function to find the element with minimum sum of differences between any elements in the array ; Stores the required X and sum of absolute differences ; Calculate sum of array elements ; The sum of absolute differences can 't be greater than sum ; Update res that gives the minimum sum ; If the current difference is less than the previous difference ; Update min_diff and res ; Print the resultant value ; Driver Code
function minimumDiff ( arr , N ) { let res = arr [ 0 ] , sum = 0 ; for ( let i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; let min_diff = sum ; for ( let i = 0 ; i < N ; i ++ ) { if ( Math . abs ( sum - ( arr [ i ] * N ) ) < min_diff ) { min_diff = Math . abs ( sum - ( arr [ i ] * N ) ) ; res = arr [ i ] ; } } document . write ( res ) ; } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let N = arr . length ; minimumDiff ( arr , N ) ;