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.
[1, 0, 1, 1, 0] // → 4 (flip a 0 to join 1,1)
[1, 1, 1] // → 3
[0, 0] // → 1 (flip one 0)
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.
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.
"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 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.
right; if the new element is zero, increment the zero counter.right reaches the end.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.
def max_ones_with_single_flip(nums):
left = 0
zeros = 0
best = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > 1:
if nums[left] == 0:
zeros -= 1
left += 1
if right - left + 1 > best:
best = right - left + 1
return best
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.