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}.