Maximum Consecutive Ones III

Maximum consecutive ones III. Find maximum consecutive ones in an array of 0s and 1s, If k flip is allowed.

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 we can flip k zeros.

For example:

Input – {1, 1, 0, 0, 0, 1, 1, 1, 1, 1}, k = 2 (We can flip two zeros)

Output: 7

Explanation:

In this example, If we can flip at most k (which is 2) zero. By flipping the zeros, here we can form following subarrays.

{1, 1, 1, 1} -> From index 0 to 3 (zero is present at index 2 and 3)

One subarray is from index 1 to 3 -> {1, 1, 1}

Another subarray is from index 2 to 3 (As both the element at this index is zero) -> {1, 1}

From index 3 to 9 -> {1, 1, 1, 1, 1, 1, 1}

Out of these, the maximum number of consecutive 1s in an array is 7 {1, 1, 1, 1, 1, 1, 1}.

This problem is the variation of maximum consecutive ones II.

Maximum Consecutive Ones solution

In this tutorial, I am going to discuss a sliding window approach to solve this problem. Also, i have explained it’s java code.

Max consecutive ones iii video tutorial

Find longest substring without repeating characters

Maximum Consecutive Ones III (If K Flip is Allowed) – Java Code

This problem can be efficiently solved using sliding window approach. The idea here is to maintain a window containing at most k zeroes at any point (As k flip is allowed). For this we need two pointers start and end.

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

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

Max consecutive ones iii video tutorial

Programming video tutorials

Maximum Consecutive Ones III LeetCode Solution

Maximum consecutive ones LeetCode solution.

Most Popular Data Structure Books

Data structure made easy

Cracking the coding interview

Tagged , . Bookmark the permalink.

About WebRewrite

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