Maximum sum of absolute difference of any permutation
Last Updated :
27 Mar, 2023
Given an array, we need to find the maximum sum of the absolute difference of any permutation of the given array.
Examples:
Input : { 1, 2, 4, 8 }
Output : 18
Explanation : For the given array there are
several sequence possible
like : {2, 1, 4, 8}
{4, 2, 1, 8} and some more.
Now, the absolute difference of an array sequence will be
like for this array sequence {1, 2, 4, 8}, the absolute
difference sum is
= |1-2| + |2-4| + |4-8| + |8-1|
= 14
For the given array, we get the maximum value for
the sequence {1, 8, 2, 4}
= |1-8| + |8-2| + |2-4| + |4-1|
= 18
To solve this problem, we have to think greedily that how can we maximize the difference value of the elements so that we can have a maximum sum. This is possible only if we calculate the difference between some very high values and some very low values like (highest – smallest). This is the idea which we have to use to solve this problem. Let us see the above example, we will have maximum difference possible for sequence {1, 8, 2, 4} because in this sequence we will get some high difference values, ( |1-8| = 7, |8-2| = 6 .. ). Here, by placing 8(highest element) in place of 1 and 2 we get two high difference values. Similarly, for the other values, we will place next highest values in between other, as we have only one left i.e 4 which is placed at last.
Algorithm: To get the maximum sum, we should have a sequence in which small and large elements comes alternate. This is done to get maximum difference.
For the implementation of the above algorithm ->
- We will sort the array.
- Calculate the final sequence by taking one smallest element and largest element from the sorted array and make one vector array of this final sequence.
- Finally, calculate the sum of absolute difference between the elements of the array.
Below is the implementation of above idea :
C++
#include <bits/stdc++.h>
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;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
static int MaxSumDifference(Integer []a, int n)
{
List<Integer> finalSequence =
new ArrayList<Integer>();
Arrays.sort(a);
for ( int i = 0 ; i < n / 2 ; ++i) {
finalSequence.add(a[i]);
finalSequence.add(a[n - i - 1 ]);
}
if (n % 2 != 0 )
finalSequence.add(a[n/ 2 ]);
int MaximumSum = 0 ;
for ( int i = 0 ; i < n - 1 ; ++i) {
MaximumSum = MaximumSum +
Math.abs(finalSequence.get(i)
- finalSequence.get(i + 1 ));
}
MaximumSum = MaximumSum +
Math.abs(finalSequence.get(n - 1 )
- finalSequence.get( 0 ));
return MaximumSum;
}
public static void main(String args[])
{
Integer []a = { 1 , 2 , 4 , 8 };
int n = a.length;
System.out.print(MaxSumDifference(a, n));
}
}
|
Python3
import numpy as np
class GFG:
def MaxSumDifference(a,n):
np.sort(a);
j = 0
finalSequence = [ 0 for x in range (n)]
for i in range ( 0 , int (n / 2 )):
finalSequence[j] = a[i]
finalSequence[j + 1 ] = a[n - i - 1 ]
j = j + 2
if (n % 2 ! = 0 ):
finalSequence[n - 1 ] = a[n / / 2 + 1 ]
MaximumSum = 0
for i in range ( 0 , n - 1 ):
MaximumSum = (MaximumSum +
abs (finalSequence[i] -
finalSequence[i + 1 ]))
MaximumSum = (MaximumSum +
abs (finalSequence[n - 1 ] -
finalSequence[ 0 ]));
print (MaximumSum)
a = [ 1 , 2 , 4 , 8 ]
n = len (a)
GFG.MaxSumDifference(a, n);
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int MaxSumDifference( int []a, int n)
{
List< int > finalSequence = new List< int >();
Array.Sort(a);
for ( int i = 0; i < n / 2; ++i) {
finalSequence.Add(a[i]);
finalSequence.Add(a[n - i - 1]);
}
if (n % 2 != 0)
finalSequence.Add(a[n/2]);
int MaximumSum = 0;
for ( int 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;
}
public static void Main()
{
int []a = { 1, 2, 4, 8 };
int n = a.Length;
Console.WriteLine(MaxSumDifference(a, n));
}
}
|
PHP
<?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 ) . "\n" ;
?>
|
Javascript
<script>
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){
double flr = Math.floor(n/2);
finalSequence.push(a[flr]);
}
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));
</script>
|
Complexities Analysis:
- Time Complexity: O(nlogn), required to sort the array
- Auxiliary Space: O(n), as extra space of size n is used
Optimization:
The space can be optimized to O(1), since we are constructing new array by putting alternate term one behind the other, instead to constructing new array we can just pick the alternates from the array using 2 pointer technique and calculate the answer:
Follow the below steps to implement the above idea:
- Sort the array
- Initialize 2 variable i=0, j = size – 1
- Set a flag (true if we will increment i and false if we will decrement j) in order to track which variable needs to be changed. since after first move we will select next min value i.e. increment i, it will be initialised as true;
- Run the while loop and calculate sum for every i and j, and change i and j accordingly
- After the loop we need to calculate the difference of middle element and first. this will be done separately.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long int maxSum( int arr[], int n)
{
sort(arr, arr + n);
int i = 0, j = n - 1;
bool off = true ;
long long int sum = 0;
while (i < j) {
sum += abs (arr[i] - arr[j]);
if (!off) {
j--;
}
else {
i++;
}
off = !off;
}
sum += abs (arr[i] - arr[0]);
return sum;
}
int main()
{
int a[] = { 1, 2, 4, 8 };
int n = sizeof (a) / sizeof (a[0]);
cout << maxSum(a, n) << endl;
}
|
Java
import java.io.*;
import java.util.Arrays;
class GFG {
public static int maxSum( int [] arr, int n) {
Arrays.sort(arr);
int i = 0 , j = n - 1 , sum = 0 ;
boolean off = true ;
while (i < j) {
sum += Math.abs(arr[i] - arr[j]);
if (off) {
i++;
} else {
j--;
}
off = !off;
}
sum += Math.abs(arr[ 0 ] - arr[n/ 2 ]);
return sum;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 4 , 8 };
System.out.println(maxSum(arr, arr.length));
}
}
|
Python3
def maxSum(arr, n):
arr.sort()
i = 0
j = n - 1
off = True
sum = 0
while (i < j):
sum + = abs (arr[i] - arr[j])
if (off = = False ):
j - = 1
else :
i + = 1
off = not off
sum + = abs (arr[i] - arr[ 0 ])
return sum
a = [ 1 , 2 , 4 , 8 ]
n = len (a)
print (maxSum(a, n))
|
C#
using System;
class Program {
static int maxSum( int [] arr, int n)
{
Array.Sort(arr);
int i = 0, j = n - 1, sum = 0;
bool off = true ;
while (i < j) {
sum += Math.Abs(arr[i] - arr[j]);
if (off) {
i++;
}
else {
j--;
}
off = !off;
}
sum += Math.Abs(arr[0] - arr[n / 2]);
return sum;
}
static void Main( string [] args)
{
int [] arr = { 1, 2, 4, 8 };
Console.WriteLine(maxSum(arr, arr.Length));
}
}
|
Javascript
function maxSum(arr,n) {
arr.sort();
let i = 0;
let j = n - 1;
let sum = 0;
let off = true ;
while (i < j) {
sum += Math.abs(arr[i] - arr[j]);
if (off) {
i++;
} else {
j--;
}
off = !off;
}
sum += Math.abs(arr[0] - arr[n/2]);
return sum;
}
let arr = [1,2,4,8];
console.log(maxSum(arr, arr.length));
|
Time Complexity: O(n logn)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...