Find the longest run of ones after flipping at most one zero

Quick Overview

Given a binary array, return the length of the longest run of consecutive ones you can get by flipping at most one zero. It tests linear-time two-pointer reasoning and careful handling of edge cases such as arrays with no zeros or no ones.

Find the longest run of ones after flipping at most one zero

Company: Yandex

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given a binary array `nums`, return the maximum number of consecutive `1`s in the array if you can flip at most one `0`. A flip changes a single `0` into a `1`. You may flip one `0` or none at all. ### Function Signature ```python def find_max_consecutive_ones(nums: list[int]) -> int: ``` ### Constraints - `1 <= len(nums) <= 10^5` - Each `nums[i]` is either `0` or `1`. ### Examples ```text Input: nums = [1,0,1,1,0] Output: 4 ``` Flipping the `0` at index 1 gives `[1,1,1,1,0]`, which has a run of four `1`s. Flipping the `0` at index 4 instead gives `[1,0,1,1,1]`, whose longest run is only 3, so the best result is 4. ```text Input: nums = [1,0,1,1,0,1] Output: 4 ``` Flipping index 1 gives `[1,1,1,1,0,1]` and flipping index 4 gives `[1,0,1,1,1,1]`. Both have a longest run of 4, and one flip can never join all three groups of `1`s. ```text Input: nums = [0,0,0] Output: 1 ``` The array has no `1`s, so the best you can do is flip one `0` and get a run of length 1.

Overview: Given a binary array, return the length of the longest run of consecutive ones you can get by flipping at most one zero. It tests linear-time two-pointer reasoning and careful handling of edge cases such as arrays with no zeros or no ones.

Yandex logo
Yandex
Nov 25, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given a binary array nums, return the maximum number of consecutive 1s in the array if you can flip at most one 0.

A flip changes a single 0 into a 1. You may flip one 0 or none at all.

Function Signature

def find_max_consecutive_ones(nums: list[int]) -> int:

Constraints

  • 1 <= len(nums) <= 10^5
  • Each nums[i] is either 0 or 1 .

Examples

Input: nums = [1,0,1,1,0]
Output: 4

Flipping the 0 at index 1 gives [1,1,1,1,0], which has a run of four 1s. Flipping the 0 at index 4 instead gives [1,0,1,1,1], whose longest run is only 3, so the best result is 4.

Input: nums = [1,0,1,1,0,1]
Output: 4

Flipping index 1 gives [1,1,1,1,0,1] and flipping index 4 gives [1,0,1,1,1,1]. Both have a longest run of 4, and one flip can never join all three groups of 1s.

Input: nums = [0,0,0]
Output: 1

The array has no 1s, so the best you can do is flip one 0 and get a run of length 1.