Problem
Given a binary array nums
and an integer k
, return the maximum number of consecutive1
’ s in the array if you can flip at most k
0
’s.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
nums[i]
is either0
or1
.0 <= k <= nums.length
Solution
Method 1 – Sliding Window with At Most k Zero Flips
Intuition
We want the longest sequence of 1s, allowing at most k
zeros to be flipped to 1. By using a sliding window, we can efficiently track the window containing at most k
zeros and update the maximum length found.
Approach
- Initialize two pointers
l
andr
for the window, and a variablezero
to count zeros in the window. - Move the right pointer
r
through the array:- If
nums[r]
is 0, incrementzero
. - If
zero
exceedsk
, move the left pointerl
right untilzero
is at mostk
. - Update the answer with the current window size.
- If
- Return the maximum window size found.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the array, since we scan the array once. - 🧺 Space complexity:
O(1)
, as only a few variables are used.