Maximize length of Subarray of 1’s after removal of a pair of consecutive Array elements

Given a Binary array arr[] consisting of N elements, the task is to find the maximum possible length of 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:
Explanation: 
Removal of the pair {0, 0} modifies the array to {1, 1, 1, 1} thus maximizing the length of longest possible subarray consisting only of 1’s.

Input: arr[] = {1, 1, 1, 0, 0, 0, 1} 
Output:
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 subarray of 1‘s . Finally print the maximum possible length of such 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 these count of 0’s obtained, update the maximum length of subarrays possible: 
    • If exactly two 0‘s are present between two subarrays, update maximum possible length by comparing to the combined length of both subarrays.
    • If exactly one 0 is present between two subarrays, update maximum possible length by comparing to the combined length of both subarrays – 1.
  • Finally, print the maixmum possible length obtained

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 continous 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; 

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for 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 continous 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 continous 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

chevron_right


Output: 

2

Time Complexity: O(N) 
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : offbeat, chitranayal