Maximize difference between the sum of absolute differences of each element with the remaining array | C # Program to implement the above approach ; 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 ; Print the result ; Driver Code
using System ; class GFG { static void findMaxDifference ( int [ ] arr , int n ) { Array . Sort ( arr ) ; int Leftsum = 0 ; int Totalsum = 0 ; int Minn = Int32 . MaxValue , Maxx = Int32 . MinValue ; for ( int i = 0 ; i < n ; i ++ ) Totalsum += arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { int leftNumbers = i ; int rightNumbers = n - i - 1 ; Totalsum = Totalsum - arr [ i ] ; int sum = ( leftNumbers * arr [ i ] ) - Leftsum + Totalsum - ( rightNumbers * arr [ i ] ) ; Minn = Math . Min ( Minn , sum ) ; Maxx = Math . Max ( Maxx , sum ) ; Leftsum += arr [ i ] ; } Console . WriteLine ( Maxx - Minn ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 7 } ; int N = arr . Length ; findMaxDifference ( arr , N ) ; } }