Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers

Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers

In this article, we look at a problem : Given an Array of Positive Integers, Find the [Maximum Difference](https://java2blog.com/maximum-difference-between-two-elements-in-array/ "Maximum Difference") between Two Adjacent Numbers.

For each pair of elements we need to compute their difference and find the Maximum value of all the differences in array.

Let us look at an example, Consider this array:

Sample Array with 10 Elements.

For the above shown array, we have to solve the given problem. Here are the steps which we will follow for the implementation:

  • Firstly, for each pair of elements, we have calculated their difference. We have calculated the Absolute Value of their difference because the array is not sorted and elements on either side can be greater or smaller.
  • In the figure above, we have shown the Diff. value for each such pair. We need to find the Maximum Value among these which for the above case is : 11 for the pair (1,12).
  • We are going to iterate through the array, Arr starting from index 1 and calculate the current difference for each pair as : Arr[i]>Arr[i] - Arr[i-1]code>. We have a max_diff variable which maintains the maximum of all the differences, on each iteration we update the max_diff with current difference.

Note: To calculate the Absolute Value we use Math.abs() in java. The approach is for only Positive Values in the array.

Now, let us have a quick look at the implementation:

Output:

We implement the same example discussed above in code. Let us analyze the complexity of the code.

Time Complexity: We do a simple single traversal of the array which takes linear time so the time complexitiy is O(n), for n elements in array.

That’s it for the article you can try out this code with different examples and let us know your suggestions or queries.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *