2dbi

Max Consecutive Ones III

viaLeetCode

Problem Given a binary array and an integer B, find the longest contiguous run of 1s achievable by flipping at most B zeros.

Input / Output

  • Input: int array A (0/1), int B. Output: max window length.

Constraints

  • n up to 10^5; O(n) expected.

Example

  • A = [1,0,0,1,1,0,1], B = 1 → 4 ([1,1,0,1] flipping the single 0); B = 2 → 6.

Expected approach

  • Sliding window keeping zeros-in-window <= B: extend right counting zeros; when the count exceeds B, advance left (decrementing on zeros). Window is always the best candidate ending at r → track max length. O(n)/O(1). Reframe that unlocks it: "longest window containing at most B zeros". The non-shrinking-window variant (window only grows) is a slick alternative worth mentioning. B = 0 degenerates to longest run of 1s.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account