Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Max Consecutive Ones III
mediumsliding-window
Problem
You are given a binary array nums (each element is 0 or 1) and an integer k. You may change at most k of the zeros into ones. Return the length of the longest run of consecutive ones achievable after those changes.
numshas between 1 and 100,000 entries, each0or1.kis a non-negative integer; it may exceed the number of zeros present.
Examples
nums = [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1], k = 2→6. Flip the zeros at indices 5 and 7 to join[1]at index 6 with the trailing[1, 1, 1], giving indices 5 through 10.nums = [0, 1, 0, 0], k = 3→4. Three flips are enough to turn every zero into a one.nums = [1, 0, 0, 1, 1], k = 0→2. No flips allowed; the existing run[1, 1]is the best.
Hints
- Instead of thinking about flipping, think about which contiguous stretches could become all ones. What is the only thing that limits a stretch?
- A stretch qualifies when it contains at most
kzeros. Does that property survive shrinking the stretch? - Sliding window over
nums, tracking the number of zeros inside; when it exceedsk, advance the left edge until it does not.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.