以下是一个PHP函数,可以找出给定数组中的最大顺子:
function findMaxStraight($arr) {
$maxStraight = 0;
$currentStraight = 1;
// 对数组进行排序
sort($arr);
// 遍历数组,找出最大顺子
for ($i = 0; $i < count($arr) - 1; $i++) {
// 如果当前数字与下一个数字连续,则递增当前顺子长度
if ($arr[$i] + 1 == $arr[$i+1]) {
$currentStraight++;
}
// 否则,更新最大顺子长度,并重置当前顺子长度
else {
$maxStraight = max($maxStraight, $currentStraight);
$currentStraight = 1;
}
}
// 检查最后一个顺子长度
$maxStraight = max($maxStraight, $currentStraight);
return $maxStraight;
}
// 示例用法
$array = [1, 2, 3, 5, 6, 7, 8, 10, 12, 13, 14];
$maxStraight = findMaxStraight($array);
echo "最大顺子长度为:" . $maxStraight;
在上述示例中,给定的数组为[1, 2, 3, 5, 6, 7, 8, 10, 12, 13, 14]
,最大顺子为5, 6, 7, 8
,因此最大顺子长度为4。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站