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++
// CPP implementation of
// above algorithm
#include <bits/stdc++.h>
using namespace std;
int MaxSumDifference(int a[], int n)
{
// final sequence stored in the vector
vector<int> finalSequence;
// sort the original array
// so that we can retrieve
// the large elements from
// the end of array elements
sort(a, a + n);
// 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.
for (int i = 0; i < n / 2; ++i) {
finalSequence.push_back(a[i]);
finalSequence.push_back(a[n - i - 1]);
}
// If there are odd elements, push the
// middle element at the end.
if (n % 2 != 0)
finalSequence.push_back(a[n/2]);
// variable to store the
// maximum sum of absolute
// difference
int MaximumSum = 0;
// In this loop absolute difference
// of elements for the final sequence
// is calculated.
for (int i = 0; i < n - 1; ++i) {
MaximumSum = MaximumSum + abs(finalSequence[i] -
finalSequence[i + 1]);
}
// absolute difference of last element
// and 1st element
MaximumSum = MaximumSum + abs(finalSequence[n - 1] -
finalSequence[0]);
// return the value
return MaximumSum;
}
// Driver function
int main()
{
int a[] = { 1, 2, 4, 8 };
int n = sizeof(a) / sizeof(a[0]);
cout << MaxSumDifference(a, n) << endl;
}
Java
// Java implementation of
// above algorithm
import java.io.*;
import java.util.*;
public class GFG {
static int MaxSumDifference(Integer []a, int n)
{
// final sequence stored in the vector
List<Integer> finalSequence =
new ArrayList<Integer>();
// sort the original array
// so that we can retrieve
// the large elements from
// the end of array elements
Arrays.sort(a);
// 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.
for (int i = 0; i < n / 2; ++i) {
finalSequence.add(a[i]);
finalSequence.add(a[n - i - 1]);
}
// If there are odd elements, push the
// middle element at the end.
if (n % 2 != 0)
finalSequence.add(a[n/2]);
// variable to store the
// maximum sum of absolute
// difference
int MaximumSum = 0;
// In this loop absolute difference
// of elements for the final sequence
// is calculated.
for (int i = 0; i < n - 1; ++i) {
MaximumSum = MaximumSum +
Math.abs(finalSequence.get(i)
- finalSequence.get(i + 1));
}
// absolute difference of last element
// and 1st element
MaximumSum = MaximumSum +
Math.abs(finalSequence.get(n - 1)
- finalSequence.get(0));
// return the value
return MaximumSum;
}
// Driver Code
public static void main(String args[])
{
Integer []a = { 1, 2, 4, 8 };
int n = a.length;
System.out.print(MaxSumDifference(a, n));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
import numpy as np
class GFG:
def MaxSumDifference(a,n):
# sort the original array
# so that we can retrieve
# the large elements from
# the end of array elements
np.sort(a);
# 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.
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 there are odd elements, push the
# middle element at the end.
if (n % 2 != 0):
finalSequence[n-1] = a[n//2 + 1]
# variable to store the
# maximum sum of absolute
# difference
MaximumSum = 0
# In this loop absolute
# difference of elements
# for the final sequence
# is calculated.
for i in range(0, n - 1):
MaximumSum = (MaximumSum +
abs(finalSequence[i] -
finalSequence[i + 1]))
# absolute difference of last
# element and 1st element
MaximumSum = (MaximumSum +
abs(finalSequence[n - 1] -
finalSequence[0]));
# return the value
print (MaximumSum)
# Driver Code
a = [ 1, 2, 4, 8 ]
n = len(a)
GFG.MaxSumDifference(a, n);
# This code is contributed
# by Prateek Bajaj
C#
// C# implementation of
// above algorithm
using System;
using System.Collections.Generic;
class GFG {
static int MaxSumDifference(int []a, int n)
{
// final sequence stored in the vector
List<int> finalSequence = new List<int>();
// sort the original array
// so that we can retrieve
// the large elements from
// the end of array elements
Array.Sort(a);
// 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.
for (int i = 0; i < n / 2; ++i) {
finalSequence.Add(a[i]);
finalSequence.Add(a[n - i - 1]);
}
// If there are odd elements, push the
// middle element at the end.
if (n % 2 != 0)
finalSequence.Add(a[n/2]);
// variable to store the
// maximum sum of absolute
// difference
int MaximumSum = 0;
// In this loop absolute difference
// of elements for the final sequence
// is calculated.
for (int i = 0; i < n - 1; ++i) {
MaximumSum = MaximumSum + Math.Abs(finalSequence[i] -
finalSequence[i + 1]);
}
// absolute difference of last element
// and 1st element
MaximumSum = MaximumSum + Math.Abs(finalSequence[n - 1] -
finalSequence[0]);
// return the value
return MaximumSum;
}
// Driver Code
public static void Main()
{
int []a = { 1, 2, 4, 8 };
int n = a.Length;
Console.WriteLine(MaxSumDifference(a, n));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// PHP implementation of above algorithm
function MaxSumDifference(&$a, $n)
{
// final sequence stored in the vector
$finalSequence = array();
// sort the original array so that we
// can retrieve the large elements from
// the end of array elements
sort($a);
// 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.
for ($i = 0; $i < $n / 2; ++$i)
{
array_push($finalSequence, $a[$i]);
array_push($finalSequence, $a[$n - $i - 1]);
}
// If there are odd elements, push the
// middle element at the end.
if ($n % 2 != 0)
array_push($finalSequence, $a[$n-1]);
// variable to store the maximum sum
// of absolute difference
$MaximumSum = 0;
// In this loop absolute difference
// of elements for the final sequence
// is calculated.
for ($i = 0; $i < $n - 1; ++$i)
{
$MaximumSum = $MaximumSum + abs($finalSequence[$i] -
$finalSequence[$i + 1]);
}
// absolute difference of last element
// and 1st element
$MaximumSum = $MaximumSum + abs($finalSequence[$n - 1] -
$finalSequence[0]);
// return the value
return $MaximumSum;
}
// Driver Code
$a = array(1, 2, 4, 8 );
$n = sizeof($a);
echo MaxSumDifference($a, $n) . "\n";
// This code is contributed by ita_c
?>
JavaScript
<script>
// Javascript implementation of
// above algorithm
function MaxSumDifference(a,n)
{
// final sequence stored in the vector
let finalSequence = [];
// sort the original array
// so that we can retrieve
// the large elements from
// the end of array elements
a.sort(function(a,b){return a-b;});
// 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.
for (let i = 0; i < n / 2; ++i) {
finalSequence.push(a[i]);
finalSequence.push(a[n - i - 1]);
}
// If there are odd elements, push the
// middle element at the end.
if (n % 2 != 0){
double flr = Math.floor(n/2);
finalSequence.push(a[flr]);
}
// variable to store the
// maximum sum of absolute
// difference
let MaximumSum = 0;
// In this loop absolute difference
// of elements for the final sequence
// is calculated.
for (let i = 0; i < n - 1; ++i) {
MaximumSum = MaximumSum +
Math.abs(finalSequence[i]
- finalSequence[i+1]);
}
// absolute difference of last element
// and 1st element
MaximumSum = MaximumSum +
Math.abs(finalSequence[n-1]
- finalSequence[0]);
// return the value
return MaximumSum;
}
// Driver Code
let a=[1, 2, 4, 8 ];
let n = a.length;
document.write(MaxSumDifference(a, n));
// This code is contributed by rag2127
</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++
// CPP implementation of
// above algorithm
#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;
}
// Driver function
int main()
{
int a[] = { 1, 2, 4, 8 };
int n = sizeof(a) / sizeof(a[0]);
cout << maxSum(a, n) << endl;
}
Java
/*package whatever //do not write package name here */
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));
}
}
// This code is contributed by rishabhtiwari759.
Python3
# Python implementation of above algorithm
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
# Driver function
a = [1, 2, 4, 8]
n = len(a)
print(maxSum(a, n))
# This code is contributed by Tapesh(tapeshdua420)
C#
// C# implementation of
// above algorithm
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));
}
}
// This code is contributed by Tapesh(tapeshdua420)
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));
// This code is contributed by aadityaburujwale.
Time Complexity: O(n logn)
Auxiliary Space: O(1)
Similar Reads
Minimum and Maximum sum of absolute differences of pairs
Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
8 min read
Minimum sum of absolute difference of pairs of two arrays
Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p
7 min read
Maximum absolute difference between sum of subarrays of size K
Given an array arr[] of size N and an integer K, the task is to find maximum absolute difference between the sum of subarrays of size K.Examples : Input: arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}, K = 3 Output: 6 Explanation:: Sum of subarray (-2, -3, 4) = -1 Sum of subarray (-3, 4, -1) = 0 Sum of subar
13 min read
Find maximum absolute difference with min sum of ratios in an Array
Given an array of positive integers arr[], the task is to find the maximum absolute difference between the pairs from the array such that the sum of their ratios is minimum. Examples: Input: arr[] = {2, 6, 3, 4, 8, 9}Output: 4Explanation: In the above example, the ratios of every pair are calculated
7 min read
Sum of minimum absolute differences in an array
Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
7 min read
Sum of absolute difference of maximum and minimum of all subarrays
Given an array arr containing N integers, the task is to find the sum of the absolute difference of maximum and minimum of all subarrays. Example: Input: arr[] = {1, 4, 3}Output: 7Explanation: The following are the six subarrays:[1] : maximum - minimum= 1 - 1 = 0[4] : maximum - minimum= 4 - 4 = 0[3]
5 min read
Maximum absolute difference of value and index sums
Given an unsorted array A of N integers, A_{1}, A_{2}, ...., A_{N}. Return maximum value of f(i, j) for all 1 ? i, j ? N. f(i, j) or absolute difference of two elements of an array A is defined as |A[i] - A[j]| + |i - j|, where |A| denotes the absolute value of A. Examples: We will calculate the val
14 min read
Minimum possible sum of absolute difference of pairs from given arrays
Given two arrays a[] and b[] of size N and M respectively (N < M), the task is to find the minimum possible sum of absolute difference of pairs formed by pairing each element of array a[] with an element of array b[] Note: Each element of each array can be considered only once. Examples: Input: a
8 min read
Sum of absolute differences of all pairs in a given array
Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array. Examples: Input : arr[] = {1, 2, 3, 4} Output: 10 Sum of |2-1| + |3-1| + |4-1| + |3-2| + |4-2| + |4-3| = 10 Input : arr[] = {1, 8, 9, 15, 16} Output: 74 Input : arr[]
11 min read
Absolute difference between given permutations of N natural numbers
Given two permutations arrays arr[] and brr[] of the first N Natural Numbers from 1 to N, the task is to find the absolute difference between the positions of their order in lexicographical order. Examples: Input: arr[] = {1, 3, 2}, brr[] = {3, 1, 2}Output: 3Explanation:There are 6 possible permutat
8 min read