Skip to main content
LeetCode 487, Medium. Topics: Array, Dynamic Programming, Sliding Window. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

Problem

Given a binary array nums, return the maximum number of consecutive 1’s in the array if you can flip at most one 0. Follow up: What if the input numbers come in one by one as an infinite stream? In other words, you can’t store all numbers coming from the stream as it’s too large to hold in memory. Could you solve it efficiently?

Examples

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026