Maximum sum of absolute difference of any permutation | CPP implementation of above algorithm ; final sequence stored in the vector ; sort the original array so that we can retrieve the large elements from the end of array elements ; In this loop first we will insert one smallest element not entered till that time in final sequence and then enter a highest element ( not entered till that time ) in final sequence so that we have large difference value . This process is repeated till all array has completely entered in sequence . Here , we have loop till n / 2 because we are inserting two elements at a time in loop . ; If there are odd elements , push the middle element at the end . ; variable to store the maximum sum of absolute difference ; In this loop absolute difference of elements for the final sequence is calculated . ; absolute difference of last element and 1 st element ; return the value ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxSumDifference ( int a [ ] , int n ) { vector < int > finalSequence ; sort ( a , a + n ) ; for ( int i = 0 ; i < n / 2 ; ++ i ) { finalSequence . push_back ( a [ i ] ) ; finalSequence . push_back ( a [ n - i - 1 ] ) ; } if ( n % 2 != 0 ) finalSequence . push_back ( a [ n / 2 ] ) ; int MaximumSum = 0 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { MaximumSum = MaximumSum + abs ( finalSequence [ i ] - finalSequence [ i + 1 ] ) ; } MaximumSum = MaximumSum + abs ( finalSequence [ n - 1 ] - finalSequence [ 0 ] ) ; return MaximumSum ; } int main ( ) { int a [ ] = { 1 , 2 , 4 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MaxSumDifference ( a , n ) << endl ; }