Rotation
Rotation
element
after an is a1. The task is to find maximum sum of the absolute difference between
consecutive elements with rearrangement of array elements allowed i.e. after any
rearrangement of array elements find |a1 – a2| + |a2 – a3| + …… + |an-1 – an| + |an
– a1|.
Input:
N = 4
a[] = {4, 2, 1, 8}
Output:
18
Explanation: Rearrangement done is {1, 8,
2, 4}. Sum of absolute difference between
consecutive elements after rearrangement =
|1 - 8| + |8 - 2| + |2 - 4| + |4 - 1| =
7 + 6 + 2 + 3 = 18.
class GFG
{
long maxSum(long arr[] ,int n)
{
Arrays.sort(arr);
long a[]=new long[n];
int count=0;
int i=0;
long l1=0;
long l2=0;
for( i=0;i<n-1;i=i+2)
{
a[i]=arr[count];
a[i+1]=arr[n-1-count];
count++;
}
if(n%2!=0)
{
a[n-1]=arr[(n/2)];
}
long sum=0;
for(i=0;i<n-1;i++)
{
sum=sum+(long)Math.abs(a[i]-a[i+1]);
}
sum=sum+(long)Math.abs(a[0]-a[n-1]);
return sum;
}
}