If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.
Given array of integers, find Maximum difference between two elements such that larger element appears after the smaller number
For example:
When you run above program, you will get below output:
For example:
1 2 3 4 |
int arr[]={14, 12, 70, 15, 95, 65, 22, 30}; Max Difference =95-12 = 83 |
Algorithm:
Lets say we have array arr[] of stock prices.
We will track two variable :minElementTillNow and maxDifference.
- minElementTillNow will be initialise to arr[0].
- Iterate over  arr[]
- If current element is greater than minElementTillNow
- calculate difference.
- If difference is greater than maxDifference then update the maxDifference.
- If current element is lesser than minElementTillNow
- update minElementTillNow with current element.
- We will get maxDifference in the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public static int calculateMaxDifferenceBetweenTwoElements(int[] arr) { int minElementTillNow=arr[0]; int maxDifference=Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { int difference=0; if(arr[i] >minElementTillNow) { difference=arr[i]-minElementTillNow; if(difference > maxDifference) { maxDifference=difference; } } else { minElementTillNow=arr[i]; } } return maxDifference; } |
Java Program to find maximum difference between two elements :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package org.arpit.java2blog; public class MaxDifferenceMain { public static void main(String[] args) { int arr[]={14, 12, 70, 15, 95, 65, 22, 30}; System.out.println("Maximum difference between two elements : "+calculateMaxDifferenceBetweenTwoElements(arr)); } public static int calculateMaxDifferenceBetweenTwoElements(int[] arr) { int minElementTillNow=arr[0]; int maxDifference=Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { int difference=0; if(arr[i] >minElementTillNow) { difference=arr[i]-minElementTillNow; if(difference > maxDifference) { maxDifference=difference; } } else { minElementTillNow=arr[i]; } } return maxDifference; } } |
1 2 3 |
Maximum difference between two elements : 83 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.