给定一个二进制数组, 计算其中最大连续 1 的个数。
示例:
输入:[1,1,0,1,1,1]
输出:3
解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
提示:
输入的数组只包含 0 和 1 。
输入数组的长度是正整数,且不超过 10,000。
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = 0
maxcount = 0
for num in nums:
if num == 1:
count += 1
maxcount = max(maxcount,count)
else:
count = 0
return max(maxcount,count)
设置一个容器
maxcount
用来存放最大连续的数字,
用max
函数比较已经存放的数字和当前连续的数字取大的数;
遍历数组,遇到1就加1,遇到0重新计算