Maximum difference between two elements


Given an array find the the maximum difference between any two elements provided larger element appears after the smaller.

Input : arr = {2, 3, 10, 6, 4, 8, 1}
Output : 8
Explanation : The maximum difference is between 10 and 2.

Input : arr = {7, 9, 5, 6, 3, 2}
Output : 2
Explanation : The maximum difference is between 9 and 7.


Concept behind:


  • We can easily find the solution in O(n) time complexity and O(1) space complexity.
  • We will keep track of minimum element found so far.
  • We compare it with the successive elements, if the difference is greater then we will update it.
  • And we check if the element is current minimum and update the minmum.
  In precise, while iterating, the element might be a minimum or maximum element. If it's maximum then the difference will obviously greater than the diff so far. Hence we keep track of minimum alone.

Code:

import java.util.*;

public class Solution {
    
    public static void main(String[] args) {
        int[] a ={2,3,10,6,1,11};
        int n = a.length;
        int diff = a[1]-a[0];
        int min = a[0];
    
        for(int i=1; i<n; i++){
            if(a[i]-min > diff){
                diff = a[i]-min;
            }
            if(a[i]<min)
                min = a[i];
        }
        
        System.out.println(diff);
       
     
    }
}

Output:
10

Illustration:







Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Find Maximum in Binary Tree