Max Ones With Single Flip

Max Ones With Single Flip

Given a binary array (only 0s and 1s), you may flip at most one 0 into a 1. Return the length of the longest run of consecutive 1s you can obtain.

maxOnesWithSingleFlip(nums)

Equivalently: the longest window containing at most one 0.

Input format: space-separated 0/1 values.

Examples

[1, 0, 1, 1, 0]        // → 4   (flip a 0 to join 1,1)
[1, 1, 1]              // → 3
[0, 0]                 // → 1   (flip one 0)

Walkthrough

Thinking it through

This sounds like it's about flipping bits, but the flip is a red herring — allowed at most once, and only useful on a zero inside a run you're extending. The real question: what's the longest stretch containing at most one zero? Flip that zero (or none needed) and you get an all-ones run.

Why brute force is wasteful

Checking every (start, end) range and counting zeros from scratch is O(n²), and most of that counting is redundant since neighboring ranges share nearly all their elements.

The reframe that makes this a sliding window

"Longest window with at most one zero" is structurally identical to counting distinct characters, just counting zeros instead. Extending the window only ever changes the count via the new element — maintain a running zero count with O(1) updates instead of recounting.

The specific shrink condition

The window is invalid once it contains more than one zero. Shrink from the left, decrementing the zero count whenever the removed element is itself a zero, until the count is back to one or zero.

Building the approach

  1. Expand by advancing right; if the new element is zero, increment the zero counter.
  2. While the counter exceeds one, shrink from the left, decrementing when a zero leaves.
  3. Once valid, compute the width and update the best.
  4. Continue until right reaches the end.

Why this is efficient and correct

Each element enters once and leaves at most once — O(n), not O(n²). Scanning every right and keeping the best considers every candidate for the optimal flip, without ever deciding which zero to flip — the window represents the run you'd get after flipping the one zero it contains.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.