#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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容