Longest Subarray of non-negative Integers

22 Jun, 2022
Given an array, return the length of the longest subarray of non-negative integersExamples : 
Input : {2, 3, 4, -1, -2, 1, 5, 6, 3}
Output : 4

The subarray [ 1, 5, 6, 3] has length 4 and 
contains no negative integers

Input : {1, 0, 0, 1, -1, -1, 0, 0, 1, 0}
Output : 4

Subarrays [1, 0, 0, 1] and [0, 0, 1, 0] have 
equal lengths but sum of first one is greater
so that will be the output.
Naive Approach: The idea is to use two nested loops, one for choosing starting index of a valid subarray (where all elements are positive) and the other for finding the ending index of a valid subarray. Keep updating the result if we find any longer valid subarray.
Below is the implementation of the above approach
Java
// Longest Subarray of non-negative Integersimport java.io.*; class GFG {    public static int longestSubarray(int[] A)    {         int n = A.length;        int result = 0;         // Iterating the array for choosing starting index        // of required subarray        for (int i = 0; i < n; i++) {            if (A[i] < 0)                continue;                       // Checking if the element is positive or            // negative            int j = i;            for (; j < n; j++) {                // if the element is negative                if (A[j] < 0) {                    --j;                    break;                }            }             // Finding the max length of the subarray            if (j - i + 1 > result) {                result = j - i + 1;            }        }        return result;    }     // Driver code    public static void main(String[] args)    {        int arr[] = { 1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0 };        int n = arr.length;        System.out.println(longestSubarray(arr));    }}
5

Time Complexity: O(N2), Where N is the length of the given arrayAuxiliary Space: O(1)
Efficient Approach: We follow a simple two-pointer window approach. Initially start index points to the starting of curr subarray i.e. a non-negative integer and traverses the array. Whenever a negative element occurs we compare it with the length of the max subarray so far and update the start and size if curr length is greater. finally, we return the subarray starting at the start of length size with the first element as the size of the subarray. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find length of the longest// subarray with non-negative numbers.#include<iostream>using namespace std; // Function that returns the longest// subarray of non-negative integersint longestSubarry(int *arr, int n){    // Initialize result    int res = 0;         // Traverse array    for (int i = 0; i < n; i++)    {        // Count of current        // non-negative integers        int curr_count = 0;                 while (i < n && arr[i] >= 0)        {            curr_count++;            i++;        }             // Update result if required.        res = max(res, curr_count);    }         return res;} // Driver codeint main(){    int arr[] = {1, 0, 4, 0, 1, -1, -1,                           0, 0, 1, 0};    int n = sizeof(arr) / sizeof(arr[0]);    cout << longestSubarry(arr, n);    return 0;}
// Java program to find length of the longest// subarray with non-negative numbers. class GFG{     // Function that returns the longest    // subarray of non-negative integers    static int longestSubarry(int arr[], int n)    {        // Initialize result        int res = 0;                 // Traverse array        for (int i = 0; i < n; i++)        {            // Count of current non-            // negative integers            int curr_count = 0;            while (i < n && arr[i] >= 0)            {                curr_count++;                i++;            }                     // Update result if required.            res = Math.max(res, curr_count);        }                 return res;    }         // Driver code    public static void main(String[] args)    {        int arr[] = {1, 0, 4, 0, 1, -1,                        -1, 0, 0, 1, 0};        int n = arr.length;        System.out.println(longestSubarry(arr, n));    }} // This code is contributed by prerna saini.
# Python program to find# length of the longest# subarray with# non-negative numbers. # Function that returns# the longest subarray# of non-negative integersdef longestSubarry(arr,n):     # Initialize result    res = 0     # Traverse array    for i in range(n):             # Count of current        # non-negative integers        curr_count = 0        while (i < n and arr[i] >= 0):                 curr_count+=1            i+=1             # Update result if required.        res = max(res, curr_count)         return res  # Driver code arr= [1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0]n = len(arr)print(longestSubarry(arr, n)) # This code is contributed# by Anant Agarwal.
// C# program to find length of the longest// subarray with non-negative numbers.using System; class GFG{     // Function that returns the longest    // subarray of non-negative integers    static int longestSubarry(int []arr, int n)    {        // Initialize result        int res = 0;                 // Traverse array        for (int i = 0; i < n; i++)        {            // Count of current non-            // negative integers            int curr_count = 0;            while (i < n && arr[i] >= 0)            {                curr_count++;                i++;            }                     // Update result if required.            res = Math.Max(res, curr_count);        }                 return res;    }         // Driver code    public static void Main()    {        int []arr = {1, 0, 4, 0, 1, -1,                        -1, 0, 0, 1, 0};        int n = arr.Length;        Console.Write(longestSubarry(arr, n));    }} // This code is contributed by nitin mittal
<?php// PHP program to find length// of the longest subarray with// non-negative numbers. // Function that returns the longest// subarray of non-negative integersfunction longestSubarry($arr, $n){    // Initialize result    $res = 0;         // Traverse array    for ($i = 0; $i < $n; $i++)    {        // Count of current        // non-negative integers        $curr_count = 0;                 while ($i < $n && $arr[$i] >= 0)        {            $curr_count++;            $i++;        }             // Update result if required.        $res = max($res, $curr_count);    }         return $res;} // Driver code$arr = array(1, 0, 4, 0, 1, -1,            -1, 0, 0, 1, 0);$n = sizeof($arr) / sizeof($arr[0]);echo longestSubarry($arr, $n); // This code is contributed by nitin mittal.?>
<script> // JavaScript program for the above approach  // Function that returns the longest// subarray of non-negative integersfunction longestSubarry(arr, n){    // Initialize result    let res = 0;         // Traverse array    for (let i = 0; i < n; i++)    {        // Count of current        // non-negative integers        let curr_count = 0;                 while (i < n && arr[i] >= 0)        {            curr_count++;            i++;        }             // Update result if required.        res = Math.max(res, curr_count);    }         return res;} // Driver code     var arr = [1, 0, 4, 0, 1, -1, -1,                           0, 0, 1, 0];    let n = arr.length;    document.write(longestSubarry(arr, n));      // This code is contributed by Potta Lokesh    </script>
5
Time Complexity: O(N), Where N is the length of the given arrayAuxiliary Space: O(1)
Exercise : Modify the above solution to print the result subarray. Also, in case two subarrays have the same count, print the subarray with a larger sum.This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
nitin mittal
lokeshpotta20
akd3257
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++