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


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[1]-Arr[0]=1, Maximum Difference=1
Arr[2]-Arr[1]=3, Maximum Difference=3
Arr[3]-Arr[2]=2, Maximum Difference=3
Arr[4]-Arr[3]=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[1]-Arr[0]=6, Maximum Difference=6
Arr[2]-Arr[1]=4, Maximum Difference=6
Arr[3]-Arr[2]=5, Maximum Difference=6
Arr[4]-Arr[3]=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[1]-Arr[0].

  • 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 max_adj_Diff(int A[],int size){
   int MaxD=A[1]-A[0];
   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
   int md=max_adj_Diff(Arr,6);
   cout<<"Maximum adjacent difference in array in its sorted form :"<<md;
   return 0;
}

Output

If we run the above code it will generate the following output −

Maximum adjacent difference in array in its sorted form: 8

Updated on: 14-Aug-2020

932 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements