Max Consecutive Ones (LeetCode 485): Solution and Explanation

Easy
Array

Given an array of 0s and 1s, return the length of the longest unbroken run of 1s.

Intuition

Think of walking along the array with a stopwatch. Every 1 keeps the stopwatch running and every 0 resets it to zero.

The value on the stopwatch at any moment is the length of the run of 1s that ends right where you stand. That is all the state you need from the past, because a 0 cuts the array into independent pieces.

The answer is the highest value the stopwatch ever shows. Keep a second number, the record, and raise it whenever the live streak beats it.

Two integers and a single pass are enough, so there is no need to find runs explicitly or store their lengths.

Approach: Running streak with a record

  1. Set cur = 0 (live streak) and best = 0 (record).
  2. For each element x, if x == 1, increment cur and set best = max(best, cur).
  3. Otherwise x == 0, so reset cur = 0.
  4. After the loop, return best.

Step-by-step example

nums = [1,1,0,1,1,1]
  1. Indices 0 and 1 are 1s, so cur becomes 1 then 2, and best follows to 2.
  2. Index 2 is a 0, so cur resets to 0. The record stays 2.
  3. Indices 3 and 4 are 1s, so cur climbs to 1 then 2, which only ties the record.
  4. Index 5 is a 1, so cur reaches 3, a new record. best = 3.
  5. The loop ends and the function returns 3.

Code: Python, Java, C++

1class Solution:
2    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
3        best = cur = 0
4        for x in nums:
5            if x == 1:
6                cur += 1
7                best = max(best, cur)
8            else:
9                cur = 0
10        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each element is visited once and does a constant amount of work.

Space

O(1)

Only the two counters cur and best are stored.

Other approaches

Track the last zero (time O(n), space O(1))

Remember the index of the most recent 0. At each 1, the current run length is i - lastZero. It is the same idea expressed with an index instead of a counter.

Split on zeros (time O(n), space O(n))

Join the array into a string and split on '0', then take the longest piece. Short to write in some languages, but it builds extra strings.

Common mistakes

  • Updating best only when a 0 is reached. If the array ends with the longest run, it is never recorded. Update on every 1, or compare once more after the loop.
  • Resetting best instead of cur when a 0 appears.
  • Returning cur at the end, which is only the length of the final run.
  • Forgetting that the array may contain no 1s at all, in which case the answer is 0.

Frequently asked questions

Why update best on every 1 instead of at each 0?

Updating on every 1 means the final run is always counted, even when the array ends with 1s. Updating only at zeros needs an extra check after the loop.

What if the array has no 1s?

cur never rises above 0, so best stays 0 and the function returns 0.

How does this relate to Max Consecutive Ones III?

In the follow-up you may flip up to k zeros. A single counter is no longer enough; you use a sliding window that shrinks whenever it contains more than k zeros.

What is the time complexity of Max Consecutive Ones?

O(n) time and O(1) extra space, since each element is visited once and only two counters are kept.