Maximize length of Subarray of 1's after removal of a pair of consecutive Array elements
Last Updated :
15 Jul, 2025
Given a binary array arr[] consisting of N elements, the task is to find the maximum possible length of a subarray of only 1’s, after deleting a single pair of consecutive array elements. If no such subarray exists, print -1.
Examples:
Input: arr[] = {1, 1, 1, 0, 0, 1}
Output: 4
Explanation:
Removal of the pair {0, 0} modifies the array to {1, 1, 1, 1}, thus maximizing the length of the longest possible subarray consisting only of 1's.
Input: arr[] = {1, 1, 1, 0, 0, 0, 1}
Output: 3
Explanation:
Removal of any consecutive pair from the subarray {0, 0, 0, 1} maintains the longest possible subarray of 1's, i.e. {1, 1, 1}.
Naive Approach:
The simplest approach to solve the problem is to generate all possible pairs of consecutive elements from the array and for each pair, calculate the maximum possible length of a subarray of 1's. Finally, print the maximum possible length of such a subarray obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach:
Follow the steps given below to solve the problem:
- Initialize an auxiliary 2D vector V.
- Keep track of all the contiguous subarrays consisting of only 1's.
- Store the length, starting index, and ending index of the subarrays.
- Now, calculate the number of 0's between any two subarrays of 1's.
- Based on the count of 0's obtained, update the maximum length of subarrays possible:
- If exactly two 0's are present between two subarrays, update the maximum possible length by comparing the combined length of both subarrays.
- If exactly one 0 is present between two subarrays, update the maximum possible length by comparing the combined length of both subarrays - 1.
- Finally, print the maximum possible length obtained
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum
// subarray length of ones
int maxLen(int A[], int N)
{
// Stores the length, starting
// index and ending index of the
// subarrays
vector<vector<int> > v;
for (int i = 0; i < N; i++) {
if (A[i] == 1) {
// S : starting index
// of the sub-array
int s = i, len;
// Traverse only continuous 1s
while (A[i] == 1 && i < N) {
i++;
}
// Calculate length of the
// sub-array
len = i - s;
// v[i][0] : Length of subarray
// v[i][1] : Starting Index of subarray
// v[i][2] : Ending Index of subarray
v.push_back({ len, s, i - 1 });
}
}
// If no such sub-array exists
if (v.size() == 0) {
return -1;
}
int ans = 0;
// Traversing through the subarrays
for (int i = 0; i < v.size() - 1; i++) {
// Update maximum length
ans = max(ans, v[i][0]);
// v[i+1][1] : Starting index of
// the next Sub-Array
// v[i][2] : Ending Index of the
// current Sub-Array
// v[i+1][1] - v[i][2] - 1 : Count of
// zeros between the two sub-arrays
if (v[i + 1][1] - v[i][2] - 1 == 2) {
// Update length of both subarrays
// to the maximum
ans = max(ans, v[i][0] + v[i + 1][0]);
}
if (v[i + 1][1] - v[i][2] - 1 == 1) {
// Update length of both subarrays - 1
// to the maximum
ans = max(ans, v[i][0] + v[i + 1][0] - 1);
}
}
// Check if the last subarray has
// the maximum length
ans = max(v[v.size() - 1][0], ans);
return ans;
}
// Driver Code
int main()
{
int arr[] = { 1, 0, 1, 0, 0, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
cout << maxLen(arr, N) << endl;
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find the maximum
// subarray length of ones
static int maxLen(int A[], int N)
{
// Stores the length, starting
// index and ending index of the
// subarrays
List<List<Integer> > v = new ArrayList<>();
for (int i = 0; i < N; i++) {
if (A[i] == 1) {
// S : starting index
// of the sub-array
int s = i, len;
// Traverse only continuous 1s
while (i < N && A[i] == 1) {
i++;
}
// Calculate length of the
// sub-array
len = i - s;
// v[i][0] : Length of subarray
// v[i][1] : Starting Index of subarray
// v[i][2] : Ending Index of subarray
v.add(Arrays.asList(len, s, i - 1));
}
}
// If no such sub-array exists
if (v.size() == 0) {
return -1;
}
int ans = 0;
// Traversing through the subarrays
for (int i = 0; i < v.size() - 1; i++) {
// Update maximum length
ans = Math.max(ans, v.get(i).get(0));
// v[i+1][1] : Starting index of
// the next Sub-Array
// v[i][2] : Ending Index of the
// current Sub-Array
// v[i+1][1] - v[i][2] - 1 : Count of
// zeros between the two sub-arrays
if (v.get(i + 1).get(1) - v.get(i).get(2) - 1
== 2) {
// Update length of both subarrays
// to the maximum
ans = Math.max(ans,
v.get(i).get(0)
+ v.get(i + 1).get(0));
}
if (v.get(i + 1).get(1) - v.get(i).get(2) - 1
== 1) {
// Update length of both subarrays - 1
// to the maximum
ans = Math.max(
ans, v.get(i).get(0)
+ v.get(i + 1).get(0) - 1);
}
}
// Check if the last subarray has
// the maximum length
ans = Math.max(v.get(v.size() - 1).get(0), ans);
return ans;
}
// Driver Code
public static void main(String args[])
{
int arr[] = { 1, 0, 1, 0, 0, 1 };
int N = arr.length;
System.out.println(maxLen(arr, N));
}
}
// This code is contributed by offbeat
Python3
# Python3 program to implement
# the above approach
# Function to find the maximum
# subarray length of ones
def maxLen(A, N):
# Stores the length, starting
# index and ending index of the
# subarrays
v = []
i = 0
while i < N:
if (A[i] == 1):
# S : starting index
# of the sub-array
s = i
# Traverse only continuous 1s
while (i < N and A[i] == 1):
i += 1
# Calculate length of the
# sub-array
le = i - s
# v[i][0] : Length of subarray
# v[i][1] : Starting Index of subarray
# v[i][2] : Ending Index of subarray
v.append([le, s, i - 1])
i += 1
# If no such sub-array exists
if (len(v) == 0):
return -1
ans = 0
# Traversing through the subarrays
for i in range(len(v) - 1):
# Update maximum length
ans = max(ans, v[i][0])
# v[i+1][1] : Starting index of
# the next Sub-Array
# v[i][2] : Ending Index of the
# current Sub-Array
# v[i+1][1] - v[i][2] - 1 : Count of
# zeros between the two sub-arrays
if (v[i + 1][1] - v[i][2] - 1 == 2):
# Update length of both subarrays
# to the maximum
ans = max(ans, v[i][0] + v[i + 1][0])
if (v[i + 1][1] - v[i][2] - 1 == 1):
# Update length of both subarrays - 1
# to the maximum
ans = max(ans, v[i][0] + v[i + 1][0] - 1)
# Check if the last subarray has
# the maximum length
ans = max(v[len(v) - 1][0], ans)
return ans
# Driver Code
if __name__ == "__main__":
arr = [1, 0, 1, 0, 0, 1]
N = len(arr)
print(maxLen(arr, N))
# This code is contributed by chitranayal
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the maximum
// subarray length of ones
static int maxLen(int []A, int N)
{
// Stores the length, starting
// index and ending index of the
// subarrays
List<List<int>> v = new List<List<int>>();
for (int i = 0; i < N; i++)
{
if (A[i] == 1)
{
// S : starting index
// of the sub-array
int s = i, len;
// Traverse only continuous 1s
while (i < N && A[i] == 1)
{
i++;
}
// Calculate length of the
// sub-array
len = i - s;
// v[i,0] : Length of subarray
// v[i,1] : Starting Index of subarray
// v[i,2] : Ending Index of subarray
List<int> l = new List<int>{len, s, i - 1};
v.Add(l);
}
}
// If no such sub-array exists
if (v.Count == 0)
{
return -1;
}
int ans = 0;
// Traversing through the subarrays
for (int i = 0; i < v.Count - 1; i++)
{
// Update maximum length
ans = Math.Max(ans, v[i][0]);
// v[i+1,1] : Starting index of
// the next Sub-Array
// v[i,2] : Ending Index of the
// current Sub-Array
// v[i+1,1] - v[i,2] - 1 : Count of
// zeros between the two sub-arrays
if (v[i + 1][1] - v[i][2] - 1
== 2) {
// Update length of both subarrays
// to the maximum
ans = Math.Max(ans,
v[i][0]
+ v[i + 1][0]);
}
if (v[i + 1][1] - v[i][2] - 1
== 1)
{
// Update length of both subarrays - 1
// to the maximum
ans = Math.Max(
ans, v[i][0]
+ v[i + 1][0] - 1);
}
}
// Check if the last subarray has
// the maximum length
ans = Math.Max(v[v.Count - 1][0], ans);
return ans;
}
// Driver Code
public static void Main(String []args)
{
int []arr = { 1, 0, 1, 0, 0, 1 };
int N = arr.Length;
Console.WriteLine(maxLen(arr, N));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to find the maximum
// subarray length of ones
function maxLen(A, N)
{
// Stores the length, starting
// index and ending index of the
// subarrays
var v = [];
for (var i = 0; i < N; i++) {
if (A[i] == 1) {
// S : starting index
// of the sub-array
var s = i, len;
// Traverse only continuous 1s
while (A[i] == 1 && i < N) {
i++;
}
// Calculate length of the
// sub-array
len = i - s;
// v[i][0] : Length of subarray
// v[i][1] : Starting Index of subarray
// v[i][2] : Ending Index of subarray
v.push([len, s, i - 1]);
}
}
// If no such sub-array exists
if (v.length == 0) {
return -1;
}
var ans = 0;
// Traversing through the subarrays
for (var i = 0; i < v.length - 1; i++) {
// Update maximum length
ans = Math.max(ans, v[i][0]);
// v[i+1][1] : Starting index of
// the next Sub-Array
// v[i][2] : Ending Index of the
// current Sub-Array
// v[i+1][1] - v[i][2] - 1 : Count of
// zeros between the two sub-arrays
if (v[i + 1][1] - v[i][2] - 1 == 2) {
// Update length of both subarrays
// to the maximum
ans = Math.max(ans, v[i][0] + v[i + 1][0]);
}
if (v[i + 1][1] - v[i][2] - 1 == 1) {
// Update length of both subarrays - 1
// to the maximum
ans = Math.max(ans, v[i][0] + v[i + 1][0] - 1);
}
}
// Check if the last subarray has
// the maximum length
ans = Math.max(v[v.length - 1][0], ans);
return ans;
}
// Driver Code
var arr = [1, 0, 1, 0, 0, 1];
var N = arr.length;
document.write( maxLen(arr, N));
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 2:
Prefix and Suffix Arrays
Count the number of 1's between the occurrences of 0's. If we find a 0 then we need to find the maximum length of 1's if we skip those 2 consecutive elements. We can use the concepts of Prefix and Suffix arrays to solve the problem.
Find the length of consecutive 1s from the start of the array and store the count in the prefix array. Find the length of consecutive 1s from the ending of the array and store the count in the ending array.
We traverse both the arrays and find the maximum no. of 1s.
Algorithm:
- Create two arrays prefix and suffix of length n.
- Initialise prefix[0]=0,prefix[1]=0 and suffix[n-1]=0,suffix[n-2]=0. This tells us that there are no 1s before the first 2 elements and after the last 2 elements.
- Run the loop from 2 to n-1:
- If arr[i-2]==1
- else if arr[i-2]==0:
- Run the loop from n-3 to 0:
- If arr[i+2]==1
- else if arr[i-2]==0:
- Initialize answer=INT_MIN
- for i=0 to n-2: //Count the number of 1's by skipping the current and the next element.
- answer=max(answer,prefix[i+1]+suffix[i]
- print answer
Implementation:
C++
// C++ program to find the maximum count of 1s
#include <bits/stdc++.h>
using namespace std;
void maxLengthOf1s(vector<int> arr, int n)
{
vector<int> prefix(n, 0);
for (int i = 2; i < n; i++)
{
// If arr[i-2]==1 then we increment the
// count of occurrences of 1's
if (arr[i - 2]
== 1)
prefix[i] = prefix[i - 1] + 1;
// else we initialise the count with 0
else
prefix[i] = 0;
}
vector<int> suffix(n, 0);
for (int i = n - 3; i >= 0; i--)
{
// If arr[i+2]==1 then we increment the
// count of occurrences of 1's
if (arr[i + 2] == 1)
suffix[i] = suffix[i + 1] + 1;
// else we initialise the count with 0
else
suffix[i] = 0;
}
int ans = 0;
for (int i = 0; i < n - 1; i++)
{
// We get the maximum count by
// skipping the current and the
// next element.
ans = max(ans, prefix[i + 1] + suffix[i]);
}
cout << ans << "\n";
}
// Driver Code
int main()
{
int n = 6;
vector<int> arr = { 1, 1, 1, 0, 1, 1 };
maxLengthOf1s(arr, n);
return 0;
}
Java
// Java program to find the maximum count of 1s
class GFG{
public static void maxLengthOf1s(int arr[], int n)
{
int prefix[] = new int[n];
for(int i = 2; i < n; i++)
{
// If arr[i-2]==1 then we increment
// the count of occurrences of 1's
if (arr[i - 2] == 1)
prefix[i] = prefix[i - 1] + 1;
// Else we initialise the count with 0
else
prefix[i] = 0;
}
int suffix[] = new int[n];
for(int i = n - 3; i >= 0; i--)
{
// If arr[i+2]==1 then we increment
// the count of occurrences of 1's
if (arr[i + 2] == 1)
suffix[i] = suffix[i + 1] + 1;
// Else we initialise the count with 0
else
suffix[i] = 0;
}
int ans = 0;
for(int i = 0; i < n - 1; i++)
{
// We get the maximum count by
// skipping the current and the
// next element.
ans = Math.max(ans, prefix[i + 1] +
suffix[i]);
}
System.out.println(ans);
}
// Driver code
public static void main(String[] args)
{
int n = 6;
int arr[] = { 1, 1, 1, 0, 1, 1 };
maxLengthOf1s(arr, n);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python program to find the maximum count of 1s
def maxLengthOf1s(arr, n):
prefix = [0 for i in range(n)]
for i in range(2, n):
# If arr[i-2]==1 then we increment
# the count of occurrences of 1's
if(arr[i - 2] == 1):
prefix[i] = prefix[i - 1] + 1
# Else we initialise the count with 0
else:
prefix[i] = 0
suffix = [0 for i in range(n)]
for i in range(n - 3, -1, -1):
# If arr[i+2]==1 then we increment
# the count of occurrences of 1's
if(arr[i + 2] == 1):
suffix[i] = suffix[i + 1] + 1
# Else we initialise the count with 0
else:
suffix[i] = 0
ans = 0
for i in range(n - 1):
# We get the maximum count by
# skipping the current and the
# next element.
ans = max(ans, prefix[i + 1] + suffix[i])
print(ans)
# Driver code
n = 6
arr = [1, 1, 1, 0, 1, 1]
maxLengthOf1s(arr, n)
# This code is contributed by avanitrachhadiya2155
C#
// C# program to find the maximum count of 1s
using System;
class GFG{
static void maxLengthOf1s(int[] arr, int n)
{
int[] prefix = new int[n];
for(int i = 2; i < n; i++)
{
// If arr[i-2]==1 then we increment
// the count of occurrences of 1's
if (arr[i - 2] == 1)
prefix[i] = prefix[i - 1] + 1;
// Else we initialise the count with 0
else
prefix[i] = 0;
}
int[] suffix = new int[n];
for(int i = n - 3; i >= 0; i--)
{
// If arr[i+2]==1 then we increment
// the count of occurrences of 1's
if (arr[i + 2] == 1)
suffix[i] = suffix[i + 1] + 1;
// Else we initialise the count with 0
else
suffix[i] = 0;
}
int ans = 0;
for(int i = 0; i < n - 1; i++)
{
// We get the maximum count by
// skipping the current and the
// next element.
ans = Math.Max(ans, prefix[i + 1] + suffix[i]);
}
Console.WriteLine(ans);
}
// Driver code
static void Main()
{
int n = 6;
int[] arr = { 1, 1, 1, 0, 1, 1 };
maxLengthOf1s(arr, n);
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// Javascript program to find
// the maximum count of 1s
function maxLengthOf1s(arr, n)
{
let prefix = new Array(n);
prefix.fill(0);
for(let i = 2; i < n; i++)
{
// If arr[i-2]==1 then we increment
// the count of occurrences of 1's
if (arr[i - 2] == 1)
prefix[i] = prefix[i - 1] + 1;
// Else we initialise the count with 0
else
prefix[i] = 0;
}
let suffix = new Array(n);
suffix.fill(0);
for(let i = n - 3; i >= 0; i--)
{
// If arr[i+2]==1 then we increment
// the count of occurrences of 1's
if (arr[i + 2] == 1)
suffix[i] = suffix[i + 1] + 1;
// Else we initialise the count with 0
else
suffix[i] = 0;
}
let ans = 0;
for(let i = 0; i < n - 1; i++)
{
// We get the maximum count by
// skipping the current and the
// next element.
ans = Math.max(ans, prefix[i + 1] + suffix[i]);
}
document.write(ans);
}
let n = 6;
let arr = [ 1, 1, 1, 0, 1, 1 ];
maxLengthOf1s(arr, n);
</script>
Time Complexity :O(n)
Auxiliary Space :O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem