Leetcode PHP题解--D67 485. Max Consecutive Ones


D67 485. Max Consecutive Ones

题目链接

485. Max Consecutive Ones

题目分析

给定一个二进制数组(只含有0和1的数组),返回最长的1串。

思路

逐个遍历,若为1则计数。遇到0则判断当前计数是否大于之前记录的最大数字,并置零。

返回最大数。

最终代码

<?php
class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function findMaxConsecutiveOnes($nums) {
        $max = 0;
        $current = 0;
        foreach($nums as $val){
            if($val == 1){
                $current++;
                if($current>$max){
                    $max = $current;
                }
            }
            else{
                $current = 0;
            }
        }
        return $max;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode动态规划之PHP解析(152. Maximum Product Subarray)

>> 下一篇: Leetcode动态规划之PHP解析(123. Best Time to Buy and Sell Stock III)