开发者

How to get the greatest difference among a list of ordered numbers in PHP?

For example,

1,3,开发者_C百科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)
{}


You got a lot of different options:

  • Sort the array, then compare the first and the last element
    1. For each element, compare it to each subsequent element. Keep the highest difference in memory.
    2. Implement some kind of merge-sort, but return the difference instead of the original sorted values.


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;
    }
}


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜