Maximum Consecutive Ones
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.
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'.
For each test case, return the length of the longest subarray whose all elements are 1.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10 1 <= N <= 5 * 10^4 0 <= Arr[i] <= 1 0 <= K <= N Time Limit: 1 sec
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.
- 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.
- 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.
- 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.
- At every step update the length of the longest subarray of 1’s found so far, print this value at the end.