Maximize difference between the sum of absolute differences of each element with the remaining array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxDifference ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int Leftsum = 0 ; int Totalsum = 0 ; int Min = INT_MAX , Max = INT_MIN ; 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 = min ( Min , sum ) ; Max = max ( Max , sum ) ; Leftsum += arr [ i ] ; } cout << Max - Min ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxDifference ( arr , N ) ; return 0 ; }