# Find max difference two elements

By | November 30, 2014
Share the joy
•
•
•
•
•
•

http://www.geeksforgeeks.org/amazon-interview-experience-set-149-campus-internship/

1. /*
2.  * Q2. Given an array arr[] of integers, find out the maximum difference between any
3.  * two elements such that larger element appears after the smaller number in arr[].
4.  * Print the indices of the two elements also.
5.  * Example: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (difference between 10 and 2).
6.  * If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (difference between 7 and 9).
7.  */
8. public class MaxDifferenceTwoElement {
9.     public static void main(String[] args) {
10.         int[] array = {7, 9, 5, 6, 3, 2};
11.         findMaxDifference(array);
12.     }
13.     public static void findMaxDifference(int[] array){
14.         if(array==null){
15.             return;
16.         }
17.         int min_pos = 0;    //position of min value
18.         int max_pos = 0;    //position of max value
19.         int max_gap = Integer.MIN_VALUE;
20.         for(int i=1;i<array.length;i++){
21.             if(array[i]-array[min_pos]>max_gap){
22.                 max_pos = i;
23.                 max_gap = array[i] – array[min_pos];
24.             }
25.             else if(array[i]<min_pos){
26.                 min_pos = i;
27.             }
28.         }
29.         System.out.println(max_gap);
30.     }
31. }