Maximize difference between the sum of absolute differences of each element with the remaining array | Java program for 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 ; Driven Code
import java . util . * ; class GFG { static void findMaxDifference ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int Leftsum = 0 ; int Totalsum = 0 ; int Min = Integer . MAX_VALUE , Max = Integer . MIN_VALUE ; 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 ] ) ; Min = Math . min ( Min , sum ) ; Max = Math . max ( Max , sum ) ; Leftsum += arr [ i ] ; } System . out . print ( Max - Min ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 7 } ; int N = arr . length ; findMaxDifference ( arr , N ) ; } }