Maximum sum of absolute difference of any permutation in C++


In this problem, we are given an array. Our task is to create a program to find the Maximum sum of absolute difference of any permutation in C++.

Problem Description

We will be finding all permutation of the elements of the given array. And then finding the sum of the absolute difference of adjacent elements of the array. Lastly we will return the maximum of all sums.

Let’s take an example to understand the problem,

Input

arr[] = {9, 1, 6, 3}

Output

17

Explanation

All permutations of the array with sum of absolute difference of adjacent elements.
{9, 1, 6, 3},
sum= |9-1| + |1-6| + |6-3| + |3-9| = 8+5+3+6 = 16
{9, 1, 3, 6},
sum= |9-1| + |1-3| + |3-6| + |6- 9| = 8+2+3+3 = 16
{9, 6, 1, 3},
sum= |9-6| + |6-1| + |1-3| + |3 - 9| = 3+5+2+6 = 16
{9, 6, 3, 1},
sum= |9-6| + |6-3| + |3-1| + |1 - 9| = 3+3+2+8 = 16
{9, 3, 1, 6},
sum= |9-3| + |3-1| + |1-6| + |6- 9| = 6+2+5+3 = 16
{9, 3, 6, 1},
sum= |9-3| + |3-6| + |6-1| + |1- 9| = 6+3+5+8 = 22
{1, 9, 6, 3},
sum= |1-9| + |9-6| + |6-3| + |3-1| = 8+3+3+2 = 16
{1, 9, 3, 6},
sum= |1-9| + |9-3| + |3-6| +
|6 - 1| = 8+6+3+5 = 22
{1, 6, 9, 3},
sum= |1-6| + |6-9| + |9-3| + |3 - 1| = 5+3+6+2 = 16
{1, 6, 3, 9},
sum= |1-6| + |6-3| + |3-9| + |9-1| = 5+3+6+8 = 22
{1, 3, 9, 6},
sum= |1-3| + |3-9| + |9-6| + |6-1| = 2+6+3+5 = 16
{1, 3, 6, 9},
sum= |1-3| + |3-6| + |6-9| + |9 - 1| = 2+3+3+8 = 16
..

And all permutations taking 6 and 3 are starting numbers.

Solution Approach

A simple solution to the problem can be found by finding the best way to maximize the solution. And for maximizing the solution, we need to find all the maximum absolute differences for the array. And this can be found using the absolute difference of |smallest - highest|.

Algorithm

Step 1 − Sort the array.

Step 2 − Now, the maxsum is calculated by adding the absolute difference between the smallest number and the largest number of the sorted array.

Step 3 − At the end, return the maxSum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int calcMaxSumAbsDiff(int arr[], int N){
   int maxSumArray[N];
   int j = 0, maxSum = 0;
   sort(arr, arr + N);
   for (int i = 0; i < (N/2); ++i){
      maxSumArray[j] = arr[i];
      maxSumArray[j+1] = arr[N - i - 1];
      j += 2;
   }
   if (N % 2 != 0)
      maxSumArray[j] = arr[N/2];
   for (int i = 0; i < N - 1; i++){
      maxSum += abs(maxSumArray[i] - maxSumArray[i + 1]);
   }
   maxSum += abs(maxSumArray[N - 1] - maxSumArray[0]);
   return maxSum;
}
int main(){
   int arr[] = {9, 1, 6, 3};
   int N = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum sum of absolute difference of any permutation is "<<calcMaxSumAbsDiff(arr, N);
}

Output

The maximum sum of absolute difference of any permutation is 22

Updated on: 15-Oct-2020

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements