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[].
Max Difference = Max { arr[x] - arr[y] | x > y }
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?
Below is the code in C using Divide and Conquer.
Plz. do feel free to comment.
Say you want to find the largest Difference LD(A[])
Complete Psuedocode as desired:
Divide the array in two parts A1[] and A2[].
Base Case (
length(A) == 2
):Note:
Similarly you can calculate the min and max elements in each subarray.
largest differance in array
//time complexity O(n)
//space complexity O(1)
for better understanding please visit https://www.youtube.com/watch?v=thPG6eTPf68&t=130s
We have
max { A[i] - A[j] | i > j } = max { A[i] - min { A[j] | j < i } | i }
, which yields a straightforward O(n) algorithm:Divide & Conquer is conceptionally more complicated, but also leads to a linear time solution (with a higher constant factor).