Tuesday, 26 Oct 2021

# Lexicographically smallest permutation having maximum sum of differences between adjacent elements

Lexicographically smallest permutation having maximum sum of differences between adjacent elements
Given an array arr[] of size N, the task is to find the lexicographically smallest permutation of the given array such that the sum of difference between adjacent elements is maximum.
Examples:

Input: arr[] = {1, 2, 3, 4, 5}Output: 5 2 3 4 1Explanation:Sum of difference between adjacent elements = (5 – 2) + (2 – 3) + (3 – 4) + (4 – 1) = 4.{5, 2, 3, 4, 1} is lexicographically the smallest array and 4 is the maximum sum possible.
Input: arr[] = {3, 4, 1}Output: 4 3 1Explanation:Sum of the difference between adjacent elements = (4 – 3) + (3 – 1) = 3{4, 3, 1} is the lexicographically smallest permutation of array elements possible. Maximum sum of adjacent elements possible is 3.

Naive Approach: The simplest approach is to generate all permutations of the given array and find the sum of each permutation while keeping track of the maximum sum obtained. In the end, print the lexicographically smallest permutation with the maximum sum.Time Complexity: O(N * N!)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observation:
Let the required permutation of the array be {p1, p2, p3, …, pN – 2, pN – 1, pN}.Sum of the difference of the adjacent elements, S = (p1-p2) + (p2-p3) +….+ (pN – 2 – pN – 1) + (pN – 1 – pN)                                                                             = p1 – pn

In order to maximize S, p1 should be the largest element and pNshould be the smallest element in the given array arr[]. To build the lexicographically the smallest permutation, arrange the rest of the elements in increasing order. Follow the steps below to solve the problem:
Below is the implementation of the above approach:

C++

#include
using namespace std;

void maximumSumPermutation(vector& arr)
{

int N = arr.size();

sort(arr.begin(), arr.end());

swap(arr, arr[N – 1]);

for (int i : arr) {

cout