Back to Problem
Official 2484 views

Editorial: Max Consecutive Ones

by admin ·

34

1 Intuition

Track the current run and the best run.

2 Approach

Increment the run on a 1 and reset it on a 0, updating the maximum as you go.

3 Complexity Analysis

Time O(n), Space O(1).

4 Solution Code

class Solution:
    def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
        best = cur = 0
        for x in nums:
            cur = cur + 1 if x == 1 else 0
            best = max(best, cur)
        return best

5 Code Walkthrough

The reference solution below implements the approach step by step.