I have a working solution for my problem but now I want to improve it.
Consider the array
3,4,5,9,1,2,8
I need to find the max difference between two elements at position i and j such that i < j that is I want to find max difference between two elements where the 2nd element comes after 1st element.
In the input I gave the answer is 7 because 8-1 = 7 and 8 is after 1.
The program works but when I have a very large array it takes lot of time. Can we improve on it?
function fMax($arr)
{
$sum = $arr[1] - $arr[0];
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($sum < $arr[$j] - $arr[$i])
{
$sum = $arr[$j] - $arr[$i];
}
}
}
return $sum;
}
Thanks a lot to all the answers. I have used the code by codeaddict and it works fast.
Your current approach is
O(N^2)you can improve it toO(N).You are comparing each element with every other element. Instead you can keep track of the max difference and min element seen so far.
So every time you test a new element you see
min will give a better max sum if so
update the max sum and
so far you update the min.
PHP function:
Ideone Link