Find Maximum Difference between Two Elements of an Array

Given an array of integers, find Maximum difference between two elements such that larger number appears after the smaller number. In this tutorial, I am going to discuss multiple approaches and their java code to find maximum difference between two elements.

For example :

Example 1:

arr = {2, 5, 15, 6, 4}
Output: 13

The difference between 15 and 2 is 13. Element 15 is greater than 2 and it satisfies our condition that larger number appears after the smaller number.

Example 2:

arr = {7, 9, 5, 6, 13, 2};
Output : 8

The difference between 13 and 5 is 8 (13-5).

I have also mentioned the video tutorial link at the end of this post.

Find Maximum Difference between Two Elements of an Array

Find Maximum Difference between Two Elements of an Array

METHOD 1: Using two for loops

In this approach, we are going to use two for loops to solve this problem. The time complexity of this approach is O(n2).

The time complexity of method 1 is O(n2). Can we do better than that? Yes we can solve this problem in O(n) time complexity.

Find common element in three sorted array

Find common elements in two arrays

Find Maximum Difference between Two Elements of an Array : Java Code

In this approach, instead of taking difference of the picked element with every other element, we can take the difference with the minimum element found so far. So we need to keep track of two things:

1) Maximum difference found so far.
2) Minimum number visited so far.

 

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.