Maximum Consecutive Ones II

Maximum consecutive ones II. Given an array which only consists of 0s and 1s. Write a code to find the maximum number of consecutive 1s in an array, if you can flip at most one 0.

For example:

Input: {1, 1, 0, 0, 1, 1, 1, 1, 1}

Output: 6

In this example, If we can flip at most one zero then the maximum number of consecutive 1s in an array is 6 {1, 1, 1, 1, 1, 1}.

Maximum Consecutive Ones II

How we can solve this problem? We can solve this problem using multiple approaches. In this tutorial, I am going to discuss a sliding window technique and it’s java code to solve this problem.

The explanation of this approach using a video tutorial is present at the end of this post.

Programming video tutorials

Find maximum sum of a subarray of size k

Sort an array of 0s, 1s and 2s

Maximum Consecutive Ones II – Java Code

The idea here is to maintain a window containing at most one zeroes at any point. To solve this problem using a sliding window approach, what we can do is to maintain two pointers start and end.

Initially start and end pointer points to the 0th index. Then we move the end pointer till it satisfies the condition of at most one zero. When we found more than one zero in a window, we have to move start pointer until only one zero is left in this window.

The time complexity of this approach is O(n) and its space complexity is O(1).

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.