#485. Max Consecutive Ones

https://leetcode.com/problems/max-consecutive-ones/#/description

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

说明

  • 检测到1,则认为 1s 的长度L += 1
  • 检测到0,将 1s 的长度L置零,但是在将L置零之前,需要与已保存的L_max进行比较,若此时的L>L_max,则对L_max进行更新
class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        L = 0
        L_max = 0
        for i in range(len(nums)):
            if nums[i] == 1:
                L += 1
                L_max = max(L_max, L)
            else:
                L = 0
        return L_max

你可能感兴趣的:(#485. Max Consecutive Ones)