Max Consecutive Ones

Easy · Arrays & Hashing · Explanation and code example

Iteration - II

How it works

We can simplify the logic by updating the maximum inside the loop at every step. If we see a 1, we increment the count; otherwise, we reset it to 0. After each element, we update the result. This eliminates the need for a final comparison after the loop.

Steps

  1. Initialize res and cnt to 0.
  2. For each element in the array:
    • If the element is 1, increment cnt.
    • Otherwise, set cnt to 0.
    • Update res to be the maximum of res and cnt.
  3. Return res.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Things to watch for

Forgetting the Final Comparison

When tracking consecutive ones by resetting the counter on encountering a zero, the longest sequence might end at the last element of the array. If you only update the maximum inside the loop when hitting a zero, you will miss this case. Always compare the final count with the result after the loop ends, or update the maximum on every iteration.

Resetting the Counter Incorrectly

A subtle bug is resetting the counter to 1 instead of 0 when encountering a zero, or incrementing before checking the current element. The counter should be reset to 0 when a zero is found, then the next 1 will increment it to 1. Mixing up this logic leads to off-by-one errors in the count.

Python code example

from typing import List

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        res = cnt = 0
        for num in nums:
            cnt = cnt + 1 if num else 0
            res = max(res, cnt)
        return res

C++ code example

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0, cnt = 0;
        for (int num : nums) {
            cnt = num ? cnt + 1 : 0;
            res = max(res, cnt);
        }
        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations