# Maximum adjacent difference in an array in its sorted form in C++

C++Server Side ProgrammingProgramming

We are given with an array. The array need not be sorted. The task is to find the maximum difference between adjacent elements of that array in its sorted form. So the first thing is to sort the array in increasing or decreasing order. Then we will iterate the array and calculate the adjacent difference of Arr[i+1]-Arr[i]. Then for each iteration we will compare this difference with the one which is found maximum so far.

Input − Arr[] = [ 1,5,10,2,7 ]

Output − Maximum adjacent difference in array in its sorted form is 3.

Explanation − Sorted Arr[] in increasing order = [ 1,2,5,7,10 ]. So the adjacent differences are as follows −

Arr-Arr=1, Maximum Difference=1
Arr-Arr=3, Maximum Difference=3
Arr-Arr=2, Maximum Difference=3
Arr-Arr=3, Maximum Difference=3

Input − Arr[] = [ 5,11,21,15,20 ]

Output − Maximum adjacent difference in array in its sorted form is 6.

Explanation − Sorted Arr[] in increasing order = [ 5,11,15,20,21 ]. So the adjacent differences are as follows −

Arr-Arr=6, Maximum Difference=6
Arr-Arr=4, Maximum Difference=6
Arr-Arr=5, Maximum Difference=6
Arr-Arr=1, Maximum Difference=6

## Approach used in the below program is as follows

• Input an integer array Arr[].

• Sort the array in increasing order.( sorting order does not matter here )

• Declare a variable say MaxD to store the maximum difference between adjacent elements found so far. Take its initial value as Arr-Arr.

• Start the loop, from the second element till last element index of array.

• If the calculated difference between Arr[i+1]-Arr[i]>MaxD, update MaxD .

• Continue this till we reach the second last element index.

• Print the result MaxD as maximum adjacent element difference.

## Example

#include <bits/stdc++.h>
using namespace std;
int MaxD=A-A;
for(int i=1;i<size-1;i++){
if(A[i+1]-A[i] > MaxD)
MaxD=A[i+1]-A[i];
}
return MaxD;
}
int main(){
int Arr[]={1,5,2,18,20,13};
sort(Arr,6); //this is supposed to sort array in increasing order
}
Maximum adjacent difference in array in its sorted form: 8