I have a working solution for my problem, but now I want to improve it.
Consider an array
3,4,5,9,1,2,8
I need to find the maximum difference between two elements at positions i and j such that i < j , that is, I want to find the maximum difference between two elements, where the second element comes after the 1st element.
At the input, I gave the answer 7 , because 8-1 = 7 and 8 after 1 .
The program works, but when I have a very large array, it takes a lot of time. Can we improve 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 to everyone for the answers. I used code using codeaddict and it works fast.
arrays algorithm php
Nicky
source share