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

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 Sum Subarray of Size K

Let’s discuss a interesting problem maximum sum subarray of size k

Given an array of positive integers and a positive number K. Write a code to find the maximum sum subarray of size k.

For example:

Let’s first understand what all subarrays we can form whose size is 3.

i) First subarray is {2, 1, 5} and it’s sum is 8.

ii) Second subarray is {1, 5, 1} and it’s sum is 7.

iii) Third subarray is {5, 1,3} and it’s sum is 9.

iv) Fourth subarray is {1, 3, 2} and it’s sum is 6.

Out of all these subarrays of size three, the maximum sum subarray is {5, 1, 3} and it’s sum is 9.