Maximum difference between two elements where larger element appears after the smaller element

Objective: Given an array A[], write an algorithm to find Maximum difference between two elements where larger element appears after the smaller element or in other words find A[i] and A[j] such that A[j]-A[i] is maximum where j > i.

Naive: This problem can be easily solved using two nested loops. Take each element at a time and compare it with all the other elements and keep the track of the maximum difference elements where larger element appears after the smaller element.

Time complexity is O(N^2).

Code:

Approach 2:

Divide and Conquer

We need to find the two elements A[i] and A[j] so that A[j] – A[i] is maximum and j > i

Divide the input array into 2 parts, left Half and right half.

We have divided the problem in 2 parts. Now we can conclude that for answer-

Both indexes i and j are in the left half of the array.

Both indexes i and j are in the right half of the array.

Index i is in left half and index j is in right half of the array.

Solve the above 3 sub problems recursively and final answer will the maximum of these 3 sub problems.