File: max-consecutive-ones/solution.py

Date: 2026-06-06

Time: 17:32

max-consecutive-ones/solution.py

Purpose

This file implements the solution to LeetCode 485 — Max Consecutive Ones. It owns exactly one responsibility: given a binary array (only 0s and 1s), return the length of the longest contiguous run of 1s.

Key Components

findMaxConsecutiveOnes(nums: list[int]) -> int — The sole public function. Takes a binary array, returns an integer. The naming follows LeetCode's camelCase convention rather than PEP 8, which is consistent across this repo.

Patterns

Single-pass streaming accumulator. The function uses two variables — max_streak (global best) and current (current run length) — and makes exactly one pass over the input. This is the canonical pattern for "longest run of X" problems: increment a counter on match, reset on mismatch, track the maximum.

The maxstreak update is done eagerly inside the if n == 1 branch rather than at every iteration or after the loop. This avoids a redundant comparison on every 0-element and also avoids needing a final max(maxstreak, current) after the loop — when the array ends with 1s, the update already happened on the last 1.

No standard library usage. The solution avoids itertools.groupby, max() with a generator, or other compact alternatives in favor of explicit state tracking. This is typical for LeetCode solutions optimizing for clarity about time/space complexity.

Dependencies

Imports: None. This is a pure function with zero dependencies.

Imported by: The "Imported By" list is misleadingly large — those ~400+ test files likely share a common test harness that imports all solutions, not specific usage of this function. The direct consumer is max-consecutive-ones/test_solution.py.

Flow

1. Initialize max_streak = 0 and current = 0.

2. For each element n in nums:

3. Return max_streak.

The key insight is that max_streak is only updated inside the n == 1 branch. This works because the maximum can only increase when we see a 1, never when we see a 0.

Invariants

Error Handling

None. The function assumes valid input and will raise TypeError only if nums is not iterable. There's no explicit error handling, which is standard for LeetCode solutions.

Complexity