Given a binary array nums, return the maximum number of consecutive 1‘s in the array if you can flip at most one 0.

Example 1:

Input: nums = [1,0,1,1,0]
Output: 4
Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 4
Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.

Constraints:

Problem Intuition

The goal is to find the longest stretch of consecutive 1s in a binary array, but with one twist: you are allowed to flip at most one 0 into a 1.

How the Two-Pointer Approach Works

Think of it as a Sliding Window:

Track Zeros in the Window:

When the Window Becomes Invalid:

Keep Expanding the Window:

Track the Largest Window:

Key Idea

We don’t explicitly store a “maximum length” variable. Instead:

Explanation with Example

Imagine the array: [1, 0, 1, 1, 0, 1, 1, 1]

By the end of the loop, the largest window size (r - l) will give you the result.

Final Code Here:

Max Consecutive Ones II

Time and Space Complexity

The time complexity of the given code is O(n), where n is the length of the input list nums. This efficiency is achieved because the code uses a two-pointer technique that iterates through the list only once. The pointers l (left) and r (right) move through the array without making any nested loops, thus each element is considered only once during the iteration.

The space complexity of the code is O(1), which means it uses constant additional space regardless of input size. No extra data structures that grow with the input size are used; the variables left, right, and k take up a constant amount of space.

Leave a Reply

Your email address will not be published. Required fields are marked *