Maximum Consecutive Ones

Posted: 18 Nov, 2020
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

Given a binary array 'ARR' of size 'N', your task is to find the longest sequence of continuous 1’s that can be formed by replacing at-most 'K' zeroes by ones. Return the length of this longest sequence of continuous 1’s.

Input format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.

The first line of each test case or query contains an integer 'N' representing the size of the array (ARR).

The second line contains 'N' single space-separated binary values, representing the elements in the array.

The third line contains the value of 'K'.
Output format:
For each test case, return the length of the longest subarray whose all elements are 1.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 5 * 10^4 
0 <= Arr[i] <= 1
0 <= K <= N

Time Limit: 1 sec
Approach 1

The simplest way to find the required subarray would be to consider all the possible subarrays and compare the length at every point and store the longest length. If at any point, the current element is 0 and the value of ‘K’ is greater than 0, use it to convert the current element to 1. Else if the value of K is 0 , iterate further to find the next possible subarray.

 

Algorithm : 

  1. Loop over the array and if the current element of the array is ‘1’ find the length of the longest subarray starting with the current element.
  2. If the current element is ‘0’ , and the value of ‘K’ is greater than 0 , use it to convert the current element to ‘1’ and continue.
  3. While considering any particular subarray if the value of any element is 0 and the value of K is greater than 0, reduce K by 1 and consider the current element to be 1.
  4. At every step update the length of the longest subarray of 1’s found so far, print this value at the end.
Try Problem