Maximize difference between the sum of absolute differences of each element with the remaining array | Function to maximize difference of the sum of absolute difference of an element with the rest of the elements in the array ; Sort the array in ascending order ; Stores prefix sum at any instant ; Store the total array sum ; Initialize minimum and maximum absolute difference ; Traverse the array to find the total array sum ; Traverse the array arr [ ] ; Store the number of elements to its left ; Store the number of elements to its right ; Update the sum of elements on its left ; Store the absolute difference sum ; Update the Minimum ; Update the Maximum ; Update sum of elements on its left ; Prlet the result ; Driver Code
function findMaxDifference ( arr , n ) { arr . sort ( ) ; let Leftsum = 0 ; let Totalsum = 0 ; let Min = Number . MAX_VALUE , Max = Number . MIN_VALUE ; for ( let i = 0 ; i < n ; i ++ ) Totalsum += arr [ i ] ; for ( let i = 0 ; i < n ; i ++ ) { let leftNumbers = i ; let rightNumbers = n - i - 1 ; Totalsum = Totalsum - arr [ i ] ; let sum = ( leftNumbers * arr [ i ] ) - Leftsum + Totalsum - ( rightNumbers * arr [ i ] ) ; Min = Math . min ( Min , sum ) ; Max = Math . max ( Max , sum ) ; Leftsum += arr [ i ] ; } document . write ( Max - Min ) ; } let arr = [ 1 , 2 , 4 , 7 ] ; let N = arr . length ; findMaxDifference ( arr , N ) ;