#1004

Max Consecutive Ones III

Medium Variable window with budget

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a binary array you may flip at most k zeros to ones. Return the longest run of ones you can get.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: flip at most k zeros; longest run of ones?

Why this works: it's "longest window with at most k zeros". Count zeros in the window; shrink when there are too many.

Example: [1,1,1,0,0,0,1,1,1,1,0], k = 2

window can hold two 0sbest window [0,0,1,1,1,1] after sliding → length 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Actually flipping values in the array and trying to undo them — counting is enough.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Sliding Window
🎬 Episode 10: video coming soon