Maximum Difference between adjacent elements of array program solution in C++

 A C++ Program to Find Maximum Difference between Adjacent Elements of an Array


        This is most common question in placement tests and technical interviews. In this program the size of the array an array will be provided by user and based on these inputs we need to find the maximum difference between the adjacent elements of the given array.

The solution is provided in below parts.
  1.  Logic of Code
  2.  C++ code 


Find the maximum difference between adjacent elements of an array.

Input : 

5
10 11 7 12 14

Output :

4

Explanation :

10 - 11 = -1
11 - 7 = 4
7 - 12 = -5
12 - 14 = -2


Hence the maximum difference is 4.


LOGIC :

  •  Input Size of Array
  •  Input Array 
  •  In a loop check the difference and compare with previous one
  •  Store the max difference
  •  Print the max difference

CODE :

 
 #include <iostream>
 using namespace std;

//Function to calculate max difference

 int maxdifference(int n, int arr[]){
     
    int max = 0;
    
    for(int i=0;i<n-1;i++){
        int d= arr[i]-arr[i+1];
        if(max==0){
            max=d;
        }
        else if(d>max){
            max=d;
        } 
    }
    
    return max;
 }


// Main Function
 int main() {
    int n;
    cin>>n;
    
    int arr[n];
    
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    
    
    cout<<maxdifference(n,arr)<<endl;
 }
 

***




!! SUBSCRIBE FOR MORE CODES & VIDEOS !!

Post a Comment

0 Comments