tags:

views:

100

answers:

3

For example,

1,3,6,8,11,45,99

The interval between numbers is:

2,3,2,3,34,54

So the greatest difference is 54.

How to implement this function?

function get_greatest_diff($arr_of_numbers)
{}
+2  A: 

You got a lot of different options:

  • Sort the array, then compare the first and the last element
  • For each element, compare it to each subsequent element. Keep the highest difference in memory.
  • Implement some kind of merge-sort, but return the difference instead of the original sorted values.
PatrikAkerstrand
Since the question says it is already sorted, only the second option is relevant (and correct, mind you).
Martinho Fernandes
Well, the list is sorted already. I believe the second option you suggest is fine.
Yuval F
+2  A: 

You should handle the case where the array has less than 2 elements separately:

$maxDiff = -1;
for ($i = 0; $i + 1 < count($array); $i++) {
    $diff = $array[$i + 1] - $array[$i];
    if ($diff > $maxDiff)
        $maxDiff = $diff;
    }
}
soulmerge
This would work for the given example, but if the numbers could be negative, it wouldn't. Perhaps the OP can clarify on this point.
Martinho Fernandes
Why wouldn't it? `b - a` is the distance from `a` to `b` (assuming `b > a`), no matter which sign they have: `-2 - -4 = -2 + 4 = 2`, `2 - -1 = 2 + 1 = 3`.
soulmerge
Nevermind. *goes bang his head on the wall*
Martinho Fernandes
+1  A: 

You should do something like this :

$greatest_diff = 0;

for($i = 0; $i < sizeof($arr_of_numbers) - 1; $i++)
{
    $current_diff = $arr_of_numbers[$i + 1] - $arr_of_numbers[$i];
    if($current_diff > $greatest_diff){
        $greatest_diff = $current_diff;
    }
}

echo $greatest_diff;
Ali Bozorgkhan
ouch, please fix the code formatting. Put four spaces at the beginning of each line...
Martinho Fernandes