[LeetCode]485. Max Consecutive Ones

题目

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

** Note:**

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000
难度

Easy

方法

记录每次连续1对应1的个数,保存最大值即可

python代码
class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cur = 0
        maxCount = 0
        for i in range(len(nums)):
            if nums[i]:
                cur += 1
            else:
                if cur > maxCount:
                    maxCount = cur
                cur = 0

        return max(cur, maxCount)

Solution().findMaxConsecutiveOnes([1,1,0,1,1,1]) == 3
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 女友知知跟我语音,今年特别恐惧找不到男人,脑中YY过年回家七大姑八大姨嘲讽30岁的老女人,还不把自己嫁出去,想妥协...
    DTttt阅读 418评论 0 3