485. Max Consecutive Ones
Published in
1 min readMar 25, 2019
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
and1
. - The length of input array is a positive integer and will not exceed 10,000
Solution 1: loop
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count_global = 0
count_cur = 0
for i in nums:
if i == 1:
count_cur += 1
else:
if count_cur > count_global:
count_global = count_cur
count_cur = 0
return max(count_global, count_cur)
This beats 65.74 % of python3 submissions.
Solution 2: itertools.groupby
If we use the `itertools.groupby`, it would be much easier.
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
if 1 not in nums: return 0
groups = [(key, len(list(group))) for key, group in itertools.groupby(nums) if key == 1] # [(1, 2), (0, 1), (1, 3)]
return max(groups, key=lambda s: s[1])[1]
This solution is very fast, which beats 93.44 % of python3 submissions.