Maximum sum of absolute difference of any permutation | Javascript 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 Code
function MaxSumDifference ( a , n ) { let finalSequence = [ ] ; a . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < n / 2 ; ++ i ) { finalSequence . push ( a [ i ] ) ; finalSequence . push ( a [ n - i - 1 ] ) ; } if ( n % 2 != 0 ) finalSequence . push ( a [ Math . floor ( n / 2 ) ] ) ; let MaximumSum = 0 ; for ( let i = 0 ; i < n - 1 ; ++ i ) { MaximumSum = MaximumSum + Math . abs ( finalSequence [ i ] - finalSequence [ i + 1 ] ) ; } MaximumSum = MaximumSum + Math . abs ( finalSequence [ n - 1 ] - finalSequence [ 0 ] ) ; return MaximumSum ; } let a = [ 1 , 2 , 4 , 8 ] ; let n = a . length ; document . write ( MaxSumDifference ( a , n ) ) ;