0% found this document useful (0 votes)
7 views1 page

Rotation

The document describes a problem of finding the maximum sum of absolute differences in a circular array after rearranging its elements. Given an example with an array of four elements, it demonstrates how to achieve the maximum sum through a specific rearrangement. The provided code implements a method to calculate this maximum sum by sorting the array and strategically placing elements to maximize the differences.

Uploaded by

itagianil464
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Rotation

The document describes a problem of finding the maximum sum of absolute differences in a circular array after rearranging its elements. Given an example with an array of four elements, it demonstrates how to achieve the maximum sum through a specific rearrangement. The provided code implements a method to calculate this maximum sum by sorting the array and strategically placing elements to maximize the differences.

Uploaded by

itagianil464
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

Given an array a[ ] of N elements. Consider array as a circular array i.e.

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;
}
}

You might also like