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^5nums[i]is either0or1.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
landrfor the window, and a variablezeroto count zeros in the window. - Move the right pointer
rthrough the array:- If
nums[r]is 0, incrementzero. - If
zeroexceedsk, move the left pointerlright untilzerois at mostk. - Update the answer with the current window size.
- If
- Return the maximum window size found.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the array, since we scan the array once. - 🧺 Space complexity:
O(1), as only a few variables are used.