Skip to content

visual walkthrough

Max Consecutive Ones III

MediumVariable WindowReported at: MetaGoogleMicrosoft+4

'At most k zeros' is the standard budget-constrained window.

Solve on LeetCode

The idea

You can flip k zeros into ones, so the question becomes: what is the longest stretch containing at most k zeros? That is a variable-size window.

Grow on the right; when there are more than k zeros, shrink from the left until one zero drops out.

Complexity

approachtimespace
Try every startO(n²)O(1)
Sliding windowO(n)O(1)

More walkthroughs