Given a binary array nums, return the maximum number of consecutive 1’s in the array.

Example 1

Input: nums = [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.

Example 2

Input: nums = [1,0,1,1,0,1]
Output: 2

Approach:

We iterate through the array and use a counter variable that increments every time we see number 1, and if we see number 0, we’ll reset that counter, but we also keep track of the maximum value that the counter variable has stored, and that will be the answer.

Complexity:

Time: O(n) to loop through all elements in the array
Space: O(1) for the tracking variables and references in the loop

class Solution:
    def findMaxConsecutiveOnes(self, nums):
        maxSoFar = 0
        oneCounter = 0
        for e in nums:
            if e == 1:
                oneCounter += 1
                maxSoFar = max(maxSoFar, oneCounter)
            else: # 0
                oneCounter = 0
        return maxSoFar
        
        
solution = Solution()
assert(solution.findMaxConsecutiveOnes([1,1,0,1,1,1]) == 3)
assert(solution.findMaxConsecutiveOnes([1,0,1,1,0,1]) == 2)
print('Passed all test cases')
Share This