leetcode485--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


• 理解


class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if 0 not in nums:
return len(nums)

i,j  = 0,0

maxnum = 0
cur = 0
while j<len(nums):
if nums[j]==0:
maxnum = max(maxnum, cur)
j+=1
cur = 0  # 更新当前的为0，重新记。
else:
j += 1
cur += 1

return max(maxnum, cur)



class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if 0 not in nums:
return len(nums)

i,j  = 0,0

maxnum = 0

while j<len(nums):
if nums[j]==0:
maxnum = max(maxnum, j-i)
j+=1
i = j
else:
j += 1

return max(maxnum, j-i)



class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

Max = 0
cur = 0

for x in nums:
if x:
cur += 1
else:
Max = max(cur, Max)
cur = 0
return max(Max, cur)



class Solution{
public:
int findMaxConsecutiveOnes(vector<int>& nums){
int result = 0, Max = 0;
for(int i=0;i<nums.size(); i++)
if(nums[i]){
result++;
}else{
Max = max(Max, result);
result = 0;
}
return max(Max, result)

}
};