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.

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
CodingNinjas
author
2y

I solved this question by 2 pointers by taking left and right pointers and moving the right point untill it was possible to switch the zeroes else move the left pointer

CodingNinjas
author
2y
Brute Force approach

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, ...read more

CodingNinjas
author
2y
Queue based approach

The idea is to iterate the whole array and push the indices having value as zero of the subarray considered in a queue. Keep on iterating the array until the size of the queue is l...read more

CodingNinjas
author
2y
Two - Pointer approach

The idea is to use Two - Pointer approach. Let us take a subarray [l,r] which contains at-most ‘K’ zeroes. Let our left pointer be ‘l’ and right pointer be ‘r’. We always maintai...read more

Add answer anonymously...
Amazon Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter