Open In App

Longest Subarray of non-negative Integers

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, return the length of the longest subarray of non-negative integers

Examples : 

Input : {2, 3, 4, -1, -2, 1, 5, 6, 3}
Output : 4
Explanation: 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
Explanation: 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.

Recommended Practice

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

C++




// Include header file
#include <iostream>
#include <string>
#include <vector>
  
class GFG
{
  public:
  static int longestSubarray(std::vector<int> &A)
  {
    int n = A.size();
    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
  static void main(std::vector<std::string> &args)
  {
    std::vector<int> arr{1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0};
    int n = arr.size();
    std::cout << GFG::longestSubarray(arr) << std::endl;
  }
};
int main(int argc, char **argv){
  std::vector<std::string> parameter(argv + 1, argv + argc);
  GFG::main(parameter); 
  return 0;
};
  
// This code is contributed by aadityaburujwale.


Java




// Longest Subarray of non-negative Integers
import 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));
    }
}


Python3




# Python code for Longest Subarray of non-negative Integers
def longestSubarray(A):
    n = len(A)
    result = 0
  
    # Iterating the array for choosing starting index of required subarray
    for i in range(n):
        if A[i] < 0:
            continue
  
        # Checking if the element is positive or negative
        for j in range(i, n):
            # if the element is negative
            if A[j] < 0:
                j -= 1
                break
  
        # Finding the max length of the subarray
        if j-i+1 > result:
            result = j-i+1
  
    return result
  
arr = [1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0]
n = len(arr)
print(longestSubarray(arr))
  
# This code is contributed by lokeshmvs21.


C#




// C# program to find Longest Subarray of non-negative
// Integers
using System;
public 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;
  }
  
  static public void Main()
  {
  
    // Code
    int[] arr = { 1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0 };
    int n = arr.Length;
    Console.WriteLine(longestSubarray(arr));
  }
}
  
// This code is contributed by lokeshmvs21.


Javascript




<script>
  function longestSubarray(A,n)
  {
      
    let result = 0;
  
    // Iterating the array for choosing starting index
    // of required subarray
    for (let i = 0; i < n; i++)
    {
      if (A[i] < 0)
      {
        continue;
      }
  
      // Checking if the element is positive or
      // negative
      let 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;
  }
  
    
    let arr=[1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0];
    let n = 11;
    document.write(longestSubarray(arr,n));
    
</script>


Output

5

Time Complexity: O(N2), Where N is the length of the given array
Auxiliary 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. 

Implementation:

C++




// 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 integers 
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 = max(res, curr_count);
    }
      
    return res;
}
  
// Driver code
int 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




// 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.


Python3




# Python program to find
# length of the longest
# subarray with
# non-negative numbers.
  
# Function that returns
# the longest subarray
# of non-negative integers 
def 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#




// 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
// PHP program to find length
// of the longest subarray with
// non-negative numbers.
  
// Function that returns the longest 
// subarray of non-negative integers 
function 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.
?>


Javascript




<script>
 // JavaScript program for the above approach
  
  
// Function that returns the longest 
// subarray of non-negative integers 
function 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>


Output

5

Time Complexity: O(N), Where N is the length of the given array
Auxiliary 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.



Last Updated : 16 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads