Max Consecutive Ones I

Sliding Window

Problem

Given a binary array, find the maximum number of consecutive 1s in this array.

For example:

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.

Thought Process

  • Apply sliding window technique. This is an easy problem

  • When a zero is come across, update start index

Solution

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        start = 0
        maxL = 0
        for i in range(len(nums)):
            if nums[i] == 0:
                start = i+1
            else:
                maxL = max(maxL, i-start+1)
                
        return maxL

Key Points

  • When an element is a zero, update starting position of window to be the next index

Time Complexity

Last updated