Divide and Conquer Algo to find maximum difference between two ordered elements
Posted
by
instance
on Stack Overflow
See other posts from Stack Overflow
or by instance
Published on 2014-06-05T08:47:40Z
Indexed on
2014/06/05
9:26 UTC
Read the original article
Hit count: 223
algorithm
|divide-and-conquer
Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].
Examples:
If array is
[2, 3, 10, 6, 4, 8, 1, 7]
then returned value should be 8 (Diff between 10 and 2).If array is
[ 7, 9, 5, 6, 3, 2 ]
then returned value should be 2 (Diff between 7 and 9)
My Algorithm:
I thought of using D&C algorithm. Explanation
2, 3, 10, 6, 4, 8, 1, 7
then
2,3,10,6 and 4,8,1,7
then
2,3 and 10,6 and 4,8 and 1,7
then
2 and 3 10 and 6 4 and 8 1 and 7
Here as these elements will remain in same order, i will get the maximum difference, here it's 6.
Now i will move back to merege these arrays and again find the difference between minimum of first block and maximum of second block and keep doing this till end.
I am not able to implement this in my code. can anyone please provide a pseudo code for this?
© Stack Overflow or respective owner