Maximum sum of absolute difference of any permutation | PHP 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
< ? php function MaxSumDifference ( & $ a , $ n ) { $ finalSequence = array ( ) ; sort ( $ a ) ; for ( $ i = 0 ; $ i < $ n / 2 ; ++ $ i ) { array_push ( $ finalSequence , $ a [ $ i ] ) ; array_push ( $ finalSequence , $ a [ $ n - $ i - 1 ] ) ; } if ( $ n % 2 != 0 ) array_push ( $ finalSequence , $ a [ $ n - 1 ] ) ; $ MaximumSum = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; ++ $ i ) { $ MaximumSum = $ MaximumSum + abs ( $ finalSequence [ $ i ] - $ finalSequence [ $ i + 1 ] ) ; } $ MaximumSum = $ MaximumSum + abs ( $ finalSequence [ $ n - 1 ] - $ finalSequence [ 0 ] ) ; return $ MaximumSum ; } $ a = array ( 1 , 2 , 4 , 8 ) ; $ n = sizeof ( $ a ) ; echo MaxSumDifference ( $ a , $ n ) . " STRNEWLINE " ; ? >