Write a program to find the maximum difference between two adjacent numbers in an array

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[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

Write a program to find the maximum difference between two adjacent numbers in an array

Updated on 14-Aug-2020 07:45:48

Last update on May 30 2022 10:05:51 (UTC/GMT +8 hours)

Write a JavaScript program to find the maximum difference between any two adjacent elements of a given array of integers.

Pictorial Presentation:

Write a program to find the maximum difference between two adjacent numbers in an array

Sample Solution:

HTML Code:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Find the maximum difference between any two adjacent elements of a given array of integers.</title> </head> <body> </body> </html>

JavaScript Code:

function max_difference(arr) { var max = -1; var temp; for (var i = 0; i < arr.length - 1; i++) { temp = Math.abs(arr[i] - arr[i + 1]); max = Math.max(max, temp); } return max; } console.log(max_difference([1, 2, 3, 8, 9])) console.log(max_difference([1, 2, 3, 18, 9])) console.log(max_difference([13, 2, 3, 8, 9]))

Sample Output:

5 15 11

Flowchart:

Write a program to find the maximum difference between two adjacent numbers in an array

ES6 Version:

function max_difference(arr) { let max = -1; let temp; for (let i = 0; i < arr.length - 1; i++) { temp = Math.abs(arr[i] - arr[i + 1]); max = Math.max(max, temp); } return max; } console.log(max_difference([1, 2, 3, 8, 9])) console.log(max_difference([1, 2, 3, 18, 9])) console.log(max_difference([13, 2, 3, 8, 9]))

Live Demo:

See the Pen javascript-basic-exercise-92 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a JavaScript program to find the maximum possible sum of some of its k consecutive numbers (numbers that follow each other in order.) of a given array of positive integers.
Next: Write a JavaScript program to find the maximum difference among all possible pairs of a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Creates an array of key-value pair arrays from an object

Example:

const tips_objectToEntries = obj => Object.keys(obj).map(k => [k, obj[k]]); console.log(tips_objectToEntries({ x: 1, y: 2 }));

Output:

[["x", 1], ["y", 2]]

Last update on May 27 2022 12:23:22 (UTC/GMT +8 hours)

Write a program in C to find out the maximum difference between any two elements such that larger element appears after the smaller number.

Pictorial Presentation:

Write a program to find the maximum difference between two adjacent numbers in an array

Sample Solution:

C Code:

#include <stdio.h> int maxDifference(int arr1[], int n) { int i; int min_element=arr1[0]; int diff=arr1[1]-arr1[0]; for(i=1;i<n;i++) { if(arr1[i]-min_element>diff) { diff=arr1[i]-min_element; printf("The elements which provide maximum difference is: %d, %d\n", min_element,arr1[i]); } if(arr1[i]<min_element) min_element=arr1[i]; } return diff; } int main() { int arr1[] = { 7, 9, 5, 6, 13, 2 }; int n = sizeof(arr1) / sizeof(arr1[0]); int i; //------------- print original array ------------------ printf("The given array is : "); for(i = 0; i < n; i++) { printf("%d ", arr1[i]); } printf("\n"); //------------------------------------------------------ printf("The Maximum difference between two elements in the array is: %d", maxDifference(arr1, n)); getchar(); return 0; }

Sample Output:

The given array is : 7 9 5 6 13 2 The elements which provide maximum difference is: 5, 13 The Maximum difference between two elements in the array is: 8

Flowchart:

Write a program to find the maximum difference between two adjacent numbers in an array

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a program in C to return maximum sum such that no two elements are adjacent.
Next: Write a program in C to find two numbers that occur odd number of times in an array.

What is the difficulty level of this exercise?

How can mixed data types (int, float, char, etc) be stored in an array?

You can make the array elements a discriminated union, aka tagged union.

struct { enum { is_int, is_float, is_char } type; union { int ival; float fval; char cval; } val; } my_array[10];

The type member is used to hold the choice of which member of the union is should be used for each array element. So if you want to store an int in the first element, you would do:

my_array[0].type = is_int; my_array[0].val.ival = 3;

When you want to access an element of the array, you must first check the type, then use the corresponding member of the union. A switch statement is useful:

switch (my_array[n].type) { case is_int: // Do stuff for integer, using my_array[n].ival break; case is_float: // Do stuff for float, using my_array[n].fval break; case is_char: // Do stuff for char, using my_array[n].cvar break; default: // Report an error, this shouldn't happen }

It's left up to the programmer to ensure that the type member always corresponds to the last value stored in the union.

Ref : https://bit.ly/3wcgjNF

This C Program checks 2 elements in the array such that difference between them is largest. This program finds maximum differnce between the 2 array elements.

Here is source code of the C Program to find 2 elements in the array such that difference between them is largest.. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Find 2 Elements in the Array such that Difference between them is Largest
  3.  */
  4. #include <stdio.h>
  5.  
  6. int maximum_difference(int array[], int arr_size)
  7. {
  8. int max_diff = array[1] - array[0];
  9. int i, j;
  10. for (i = 0; i < arr_size; i++)
  11. {
  12. for (j = i + 1; j < arr_size; j++)
  13. {
  14. if (array[j] - array[i] > max_diff)
  15. max_diff = array[j] - array[i];
  16. }
  17. }
  18. return max_diff;
  19. }
  20.  
  21. int main()
  22. {
  23. int array[] = {10, 15, 90, 200, 110};
  24. printf("Maximum difference is %d", maximum_difference(array, 5));
  25. getchar();
  26. return 0;
  27. }

$ cc pgm97.c $ a.out Maximum difference is 190

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

  • Get Free Certificate of Merit in C Programming
  • Participate in C Programming Certification Contest
  • Become a Top Ranker in C Programming
  • Take C Programming Tests
  • Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Write a program to find the maximum difference between two adjacent numbers in an array

Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.