⚡Flashcard Drill➔
NeetCode #225LC-487MediumSliding WindowNC Algo100
← Back to All Problems

#225 · #487 · Max Consecutive Ones II(最大连续 1 的个数 II)

📌 Problem Statement & Constraints

Given a binary array nums, return the maximum number of consecutive 1s obtainable if you can flip at most one 0. Constraints: 1 <= nums.length <= 10^5.

💡 Core Algorithmic Approaches

  1. This is Max Consecutive Ones III with k = 1: a sliding window containing at most one zero.
  2. Expand the right end; when the zero count exceeds one, shrink from the left.
  3. The window length is the candidate answer.
  4. An alternative is to track the lengths of runs of ones and combine adjacent runs separated by a single zero.

💻 Benchmark Python3 Implementation

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        l = 0
        zeros = 0
        best = 0
        for r, x in enumerate(nums):
            if x == 0:
                zeros += 1
            while zeros > 1:           # more than one zero -> invalid
                if nums[l] == 0:
                    zeros -= 1
                l += 1
            best = max(best, r - l + 1)
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each element enters and leaves the window at most once.
💾 Space Complexity
O(1): two scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Allowing two zeros: the limit is exactly one flip.
  • Decrementing the zero count for every element leaving the window: only zeros should decrement it.
  • Assuming the array contains a zero: an all-ones array works fine, since the window never needs to shrink.
  • Returning the number of ones instead of the window length: the flipped zero also counts toward the length.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

最大连续 1 的个数 II

给定一个二进制数组 nums,如果最多可以翻转一个 0,则返回数组中连续 1 的最大个数。约束:1 ≤ nums.length ≤ 10^5;nums[i] 为 0 或 1。

核心要点

  • 滑动窗口 + 零计数(标准解) :维护窗口内 0 的个数 zeros 。右指针扩展;当 zeros &gt; 1 时收缩左边界直到 zeros &lt;= 1 。
  • 为什么窗口合法条件是 zeros &lt;= 1 :最多翻转一个 0,因此窗口内 0 的个数不能超过 1。
  • 答案 :所有合法窗口的最大长度。
  • 推广 :把「1」换成 k,即为 1004 题(最多翻转 k 个 0)。本题是 k = 1 的特例。

常见陷阱

  • 忘记在收缩时递减 zeros :会导致 while 循环无法退出。
  • 把「翻转一个 0」理解为「删除一个 0」 :翻转后该位置变成 1,因此它 计入 窗口长度,无需排除。
  • 全为 1 时答案应为 n :本解中 zeros 始终为 0,窗口不收缩,答案正确为 n。
  • 全为 0 时答案应为 1 :翻转一个 0 后长度为 1,本解正确(窗口最大长度为 1)。

参考实现

class Solution:
    def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
        l = 0
        zeros = 0               # 窗口内 0 的个数
        best = 0
        for r, x in enumerate(nums):
            if x == 0:
                zeros += 1
            while zeros > 1:    # 窗口内 0 超过 1 个 -> 收缩
                if nums[l] == 0:
                    zeros -= 1
                l += 1
            if r - l + 1 > best:
                best = r - l + 1
        return best