- 作者: 你的美失控了
- 本文关键词:LeetCode,力扣,算法,算法题,数组,最大连续 1 的个数,PHP
来源:力扣(LeetCode)
目录
题目描述
给定一个二进制数组, 计算其中最大连续 1 的个数。
示例1:
输入:[1,1,0,1,1,1] 输出:3 解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
思路
遍历数组,遇到1就count++
看看count有没有超过最大纪录,超过了就更新纪录
如果遇到的不是1,就count归零
最后返回最大纪录
代码
使用PHP写的代码如下
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function findMaxConsecutiveOnes($nums) {
$max = 0; $count = 0;
foreach($nums as $v){
if($v==1){
$count++;
}else{
$max = $max>$count?$max:$count;
// $max = max($max,$count);
$count = 0;
}
}
// $max = max($max,$count);
$max = $max>$count?$max:$count;
return $max;
}
}
每天一点点