To solve this problem, we need to find the maximum number of consecutive 1's in a binary array if we can flip at most k 0's. This problem can be efficiently solved using the sliding window technique which allows us to maintain a window of elements and adjust it dynamically to keep track of the valid subarray (with at most k 0's).
Approach
- Sliding Window: Use two pointers (
leftandright) to represent the current window of elements being considered. - Zero Count: Track the number of 0's in the current window.
- Adjust Window: When the number of 0's exceeds
k, move theleftpointer to the right until the number of 0's in the window is within the allowed limit (k). - Max Length: Keep updating the maximum length of the valid window (consecutive 1's with at most
kflipped 0's) as we expand the window with therightpointer.
Solution Code
def maxConsecutiveOnes(nums, k):
left = 0
max_len = 0
zero_count = 0
for right in range(len(nums)):
# Increment zero count if current element is 0
if nums[right] == 0:
zero_count += 1
# Shrink the window from left if zero count exceeds k
while zero_count > k:
if nums[left] == 0:
zero_count -= 1
left += 1
# Update the maximum length of the valid window
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
return max_len
Explanation
- Initialization:
leftstarts at 0,max_len(to store the result) starts at 0, andzero_count(to track 0's in the window) starts at 0. - Expand Window: The
rightpointer moves from left to right. For each element, if it's a 0, incrementzero_count. - Shrink Window: If
zero_countexceedsk, move theleftpointer to the right. If the element atleftis a 0, decrementzero_count(since it's no longer in the window). - Update Max Length: For each valid window (with ≤
k0's), calculate its length and updatemax_lenif it's larger than the current value.
This approach runs in O(n) time complexity (since each element is processed at most twice: once by the right pointer and once by the left pointer) and O(1) space complexity (no additional data structures used). It efficiently handles all edge cases, including when all elements are 0's or 1's, and when k is 0.
Example: For nums = [1,1,1,0,0,0,1,1,1,1,0] and k=2, the maximum length is 6 (the subarray from index 5 to 10: 0,1,1,1,1,0 with 2 flipped 0's).
This solution is optimal and widely used for similar subarray problems involving constraints on element counts.


作者声明:本文包含人工智能生成内容。