Max Consecutive Ones

Easy

Topics
Array

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

Example 1

101102131415length 3
No window bookkeeping is needed because nothing is ever allowed inside the run.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,1,0,1,1,1]
Output: 3

Example 2

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

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is 0 or 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Track the length of the run ending at the current position. A 1 extends it; a 0 ends it. The answer is the largest value that running length ever takes.

That is the whole algorithm, and it needs two variables. The reason it is worth stating carefully is the reset: on a 0 the current run goes to 0, not to 1, and not left alone.

Approach

  1. current = 0, best = 0.
  2. For each element: current = current + 1 if it is 1, else 0; then best = max(best, current).

Dry Run

nums = [1,1,0,1,1,1]

1   current=1  best=1
1   current=2  best=2
0   current=0  best=2
1   current=1  best=2
1   current=2  best=2
1   current=3  best=3

answer 3

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two integers.

Common Pitfalls

  • Updating best only when a 0 is seen. An array ending in 1s then never records its final run — [1,1,1] returns 0.
  • Resetting current to 1 instead of 0 on a zero, which counts the zero as part of a run.
  • Returning current rather than best.
  • Assuming the array contains only 1s and 0s without it being stated. Here it is guaranteed; in the follow-up variant that allows flipping a zero, this scan becomes a sliding window.

Full Solution — all languages

class Solution:
    def findMaxConsecutiveOnes(self, nums):
        best = cur = 0
        for x in nums:
            cur = cur + 1 if x == 1 else 0
            best = max(best, cur)
        return best
SensAI
Beta
Tap the mic to stop voice mode