NeetCode #37LC-485EasyArrays & Hashing
← Back to All Problems#37 · #485 · Max Consecutive Ones(最大连续 1 的个数)
📌 Problem Statement & Constraints
Given a binary array
nums, return the maximum number of consecutive 1s in the array. Constraints: 1 <= nums.length <= 10^5, nums[i] is 0 or 1.💡 Core Algorithmic Approaches
- Keep a running counter of the current run of ones and a global best.
- On a
1, increment the counter and update the best. - On a
0, reset the counter to zero. - This is the template for all maximum-consecutive-run problems, including the sliding-window variants that allow flipping a limited number of zeros.
💻 Benchmark Python3 Implementation
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
best = cur = 0
for x in nums:
if x == 1:
cur += 1
best = max(best, cur)
else:
cur = 0 # run broken
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two counters.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting to reset on 0: the counter would accumulate across runs and overcount.
- Using a sliding window: unnecessary here since the array is binary and the constraint is exact -- a simple counter suffices.
- Initialising
bestto 1: an all-zero array must return 0.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
最大连续 1 的个数
给定一个二进制数组 nums,计算其中最大连续 1 的个数。约束:1 ≤ nums.length ≤ 10^5;nums[i] 为 0 或 1。
核心要点
- 一次遍历 + 滚动计数(标准解) :维护当前连续 1 的长度 cur 与历史最大值 best。遇到 1 则 cur 加一,遇到 0 则 cur 归零,每步更新 best。
- 为什么不需要记录区间 :题目只问长度,不需要给出区间位置,因此滚动计数足够。
- 等价写法 :把数组按 0 切分后取最长段长度,但需要额外空间且不必要。
- 变体思考 :若允许把最多 k 个 0 翻转成 1,则退化为滑动窗口问题(见 1004)。
常见陷阱
- 忘记在遇到 0 时归零 :只累加不归零会得到「1 的总个数」而不是「最大连续个数」。
- 只更新 cur 不更新 best :遍历结束后返回 cur,当数组以 0 结尾时会返回 0,结果错误。
- 误以为需要双指针记录区间 :本题不需要区间信息,双指针是过度设计。
参考实现
class Solution:
def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
best = cur = 0
for x in nums:
cur = cur + 1 if x == 1 else 0
if cur > best:
best = cur
return best