Question -
Given an array of n elements. Consider array as circular array i.e element after an is a1. The task is to find maximum sum of the difference between consecutive elements. find |a1 – a2| + |a2 – a3| + …… + |an – 1 – an| + |an – a1|.
Example -
Input : arr[] = { 4, 2, 1, 8 }
Output : 18
Rearrange given array as : { 1, 8, 2, 4 }
Sum of difference between consecutive element
= |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1|
= 7 + 6 + 2 + 3
= 18.
Input : arr[] = { 10, 12, 15 }
Output : 10Implementation -
//sum=|arr[i]-arr[i+1] |+......
#include<iostream>
using namespace std;
int calculatesum(int arr[],int n)
{
int sum=0;
for(int i=0;i<n;i++){
int temp=arr[i]-arr[i+1];
if(i==n-1)
temp=arr[n-1]-arr[0];
if(temp<0)
temp=-temp;
sum+=temp;
}
return sum;
}
int main()
{
int n;
cout<<"Enter the number of the elements : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
int sum=calculatesum(arr,n);
cout<<endl<<"Sum is : "<<sum<<endl;
return 0;
}
Time complexity - O(n)
Extra space -O(1)
Comments
Post a Comment