[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]485. Max Consecutive Ones)