Problem Description
Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.
Key Insights
- Utilize a sliding window to maintain the current segment.
- The window can contain at most one 0.
- Expand the window with the right pointer and contract it with the left pointer when the constraint is violated.
- The maximum window size observed during this process is the desired result.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(1).
Solution
We use a sliding window approach to efficiently find the longest contiguous subarray that contains at most one 0. Two pointers (left and right) define the window. As we iterate with the right pointer, counting zeros in the window, we adjust the left pointer when the count of zeros exceeds one. The length of the valid window gives us the number of consecutive 1's (considering one flipped 0), and we update the maximum length accordingly.