Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Swap And Maximise

Easy
0/40
Average time to solve is 10m
Contributed by

Problem statement

You are given a circular array consisting of N integers. You have to find the maximum sum of the absolute difference between adjacent elements with rearrangement of array element allowed i.e after rearrangement of element find the maximum value of |a1 – a2| + |a2 – a3| + …… + |an – 1– an| + |an – a1|, where a1, a2, a3… an are the elements of the array.

An array is a circular array when after the last element 'an', 'a1' appears in the array.

Detailed explanation ( Input/output format, Notes, Images )
Sample Input 1 :
``````2
4
7 2 4 5
5
8 2 7 6 1
``````
Sample Output 1 :
``````12
24
``````
Explanation for Sample Output 1 :
``````For the first test case:
To maximise the sum, one of the possible configurations is 2 7 4 5 and the maximum sum possible for the first input is 12.

For the second test case:
To maximise the sum, one of the possible configurations is 1 8 2 7 6 and the maximum sum possible for the second array is 24.
``````
Sample Input 2 :
``````1
6
4 10 1 2 9 8
``````
Sample Output 2 :
``````40
``````
Console