The Wayback Machine - https://web.archive.org/web/20210222072733/https://www.geeksforgeeks.org/length-of-longest-subarray-consisting-only-of-1s/
Skip to content
Related Articles

Related Articles

Length of longest subarray consisting only of 1s
  • Last Updated : 22 Feb, 2021

Given an array arr[] of size N, consisting of binary values, the task is to find the longest non-empty subarray consisting only of 1s after removal of a single array element.

Examples:

Input: arr[] = {1, 1, 1}
Output: 2

Input: arr[] = {0, 0, 0}
Output: 0

Approach: Follow the steps below to solve the problem:



  • Initialize three variables, newLen = 0, prevLen = 0, maxLen = 0.
  • Traverse the array arr[] by appending zero at the beginning:
    • If arr[i] = 1: Increment both newLen & prevLen by 1.
    • Otherwise:
      • Assign the maximum value to the variable maxLen.
      • Set prevLen = newLen and newLen = 0.
  • Print maxLen if maxLen < len(arr).
  • Otherwise, print maxLen – 1.

Below is the implementation of the above approach:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
  
# Utility function to find the length of
# longest subarray containing only 1s
def longestSubarrayUtil(arr):
  
    new, old, m = 0, 0, 0
  
    # Traverse the array
    for x in arr+[0]:
  
        # If array element is 1
        if x == 1:
  
            # Increment both by 1
            new += 1
            old += 1
        else:
  
            # Assign maximum value
            m = max(m, old)
  
            # Assign new to old
            # and set new to zero
            old, new = new, 0
  
    # Return the final length
    return m if m < len(arr) else m - 1
  
# Function to find length of the
# longest subarray containing only 1's
def longestSubarray(arr):
  
    # Stores the length of longest
    # subarray consisting of 1s
    len = longestSubarrayUtil(arr)
  
    # Print the length
    # of the subarray
    print(len)
  
  
# Given array
arr = [1, 1, 1]
  
# Function call to find the longest
# subarray containing only 1's
longestSubarray(arr)

chevron_right


Output:

2

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

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 Articles
Page :