382/670

382. Max Consecutive Ones II

Medium

You are given a binary array nums (every element is 0 or 1), and you are allowed to flip at most one 0 into a 1.

Return the length of the longest run of consecutive 1s you can produce with that single optional flip. Equivalently: find the longest contiguous stretch of the array that contains at most one 0.

Note the flip is optional — if the array is all 1s, the answer is simply its length, and if it is all 0s, flipping one of them yields a run of length 1.

Example 1 — one flip bridges two runsThe best window of [1, 0, 1, 1, 0] spans indices 0–3 and contains exactly one 0. Spending the flip on it welds the runs on both sides into a streak of 4.
10→1110window: at most one 0 insidei0i1i2i3i4flip the 0 at index 1:runs 1 and 2 merge → 4answer = 4

Example 1:

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

Output: 4

Explanation: Flip the 0 at index 1 to get [1, 1, 1, 1, 0] — a run of 4. Flipping the last 0 instead only joins runs of lengths 2 and 0, giving 3.

Example 2:

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

Output: 4

Explanation: Flip the 0 at index 3: [0, 1, 1, 1, 1] ends with a run of 4. Flipping the leading 0 gives only [1, 1, 1, 0, 1] with a run of 3.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • nums[i] is 0 or 1

Hints:

Rephrase the flip: you are looking for the longest window of the array that contains at most one 0 — the flip spends itself on that one 0.

Slide a window with two pointers and a count of the zeros inside. Grow the right end one step at a time; whenever the window holds two zeros, advance the left end until the older zero falls out. The answer is the largest window size ever seen.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: 4