Length of longest subarray with positive product

Given an array arr[] consisting of N integers, the task is to print the length of the longest subarray with a positive product.

Examples:

Input: arr[] ={0, 1, -2, -3, -4}
Output: 3
Explanation:
The longest subarray with positive products is: {1, -2, -3}. Therefore, the required length is 3.

Input: arr[]={-1, -2, 0, 1, 2}
Output: 2
Explanation:
The longest subarray with positive products are: {-1, -2}, {1, 2}. Therefore, the required length is 2.

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and check if its product is positive or not. Among all such subarrays, print the length of the longest subarray obtained.
Time Complexity: (N3)
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved using Dynamic Programming. The idea here is to maintain the count of positive elements and negative elements such that their product is positive. Follow the steps below to solve the problem:

  1. Initialize the variable, say res, to store the length of the longest subarray with the positive product.
  2. Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively.
  3. Iterate over the array.
  4. If arr[i] = 0: Reset the value of Pos and Neg.
  5. If arr[i] > 0: Increment Pos by 1. If at least one element is present in the subarray with the negative product, then increment Neg by 1.
  6. If arr[i] < 0: Swap Pos and Neg and increment the Neg by 1. If at least one element is present in the subarray with the positive product, then increment Pos also.
  7. Update res=max(res, Pos).

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 length of
// longest subarray whose product
// is positive
int maxLenSub(int arr[], int N)
{
    // Stores the length of current
    // subarray with positive product
    int Pos = 0;
 
    // Stores the length of current
    // subarray with negative product
    int Neg = 0;
 
    // Stores the length of the longest
    // subarray with positive product
    int res = 0;
 
    for (int i = 0; i < N; i++) {
 
        if (arr[i] == 0) {
 
            // Reset the value
            Pos = Neg = 0;
        }
 
        // If current element is positive
        else if (arr[i] > 0) {
 
            // Increment the length of
            // subarray with positive product
            Pos += 1;
 
            // If at least one element is
            // present in the subarray with
            // negative product
            if (Neg != 0) {
 
                Neg += 1;
            }
 
            // Update res
            res = max(res, Pos);
        }
 
        // If current element is negative
        else {
 
            swap(Pos, Neg);
 
            // Increment the length of subarray
            // with negative product
            Neg += 1;
 
            // If at least one element is present
            // in the subarray with positive product
            if (Pos != 0) {
 
                Pos += 1;
            }
 
            // Update res
            res = max(res, Pos);
        }
    }
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { -1, -2, -3, 0, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << maxLenSub(arr, N);
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to find the length of
# longest subarray whose product
# is positive
def maxLenSub(arr, N):
     
    # Stores the length of current
    # subarray with positive product
    Pos = 0
 
    # Stores the length of current
    # subarray with negative product
    Neg = 0
 
    # Stores the length of the longest
    # subarray with positive product
    res = 0
 
    for i in range(N):
        if (arr[i] == 0):
 
            # Reset the value
            Pos = Neg = 0
 
        # If current element is positive
        elif (arr[i] > 0):
 
            # Increment the length of
            # subarray with positive product
            Pos += 1
 
            # If at least one element is
            # present in the subarray with
            # negative product
            if (Neg != 0):
                Neg += 1
 
            # Update res
            res = max(res, Pos)
 
        # If current element is negative
        else:
            Pos, Neg = Neg, Pos
 
            # Increment the length of subarray
            # with negative product
            Neg += 1
 
            # If at least one element is present
            # in the subarray with positive product
            if (Pos != 0):
                Pos += 1
 
            # Update res
            res = max(res, Pos)
             
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ -1, -2, -3, 0, 1 ]
    N = len(arr)
     
    print(maxLenSub(arr, N))
 
# This code is contributed by mohit kumar 29

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the length of
// longest subarray whose product
// is positive
static int maxLenSub(int arr[], int N)
{
    // Stores the length of current
    // subarray with positive product
    int Pos = 0;
 
    // Stores the length of current
    // subarray with negative product
    int Neg = 0;
 
    // Stores the length of the longest
    // subarray with positive product
    int res = 0;
 
    for (int i = 0; i < N; i++)
    {
        if (arr[i] == 0)
        {
            // Reset the value
            Pos = Neg = 0;
        }
 
        // If current element is positive
        else if (arr[i] > 0)
        {
            // Increment the length of
            // subarray with positive product
            Pos += 1;
 
            // If at least one element is
            // present in the subarray with
            // negative product
            if (Neg != 0)
            {
                Neg += 1;
            }
 
            // Update res
            res = Math.max(res, Pos);
        }
 
        // If current element is negative
        else
        {
            Pos = Pos + Neg;
            Neg = Pos - Neg;
            Neg = Pos - Neg;
 
            // Increment the length of subarray
            // with negative product
            Neg += 1;
 
            // If at least one element is present
            // in the subarray with positive product
            if (Pos != 0)
            {
                Pos += 1;
            }
 
            // Update res
            res = Math.max(res, Pos);
        }
    }
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = {-1, -2, -3, 0, 1};
    int N = arr.length;
    System.out.print(maxLenSub(arr, N));
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to find the length of
// longest subarray whose product
// is positive
static int maxLenSub(int[] arr, int N)
{
    // Stores the length of current
    // subarray with positive product
    int Pos = 0;
 
    // Stores the length of current
    // subarray with negative product
    int Neg = 0;
 
    // Stores the length of the longest
    // subarray with positive product
    int res = 0;
 
    for (int i = 0; i < N; i++)
    {
        if (arr[i] == 0)
        {
            // Reset the value
            Pos = Neg = 0;
        }
 
        // If current element is positive
        else if (arr[i] > 0)
        {
            // Increment the length of
            // subarray with positive product
            Pos += 1;
 
            // If at least one element is
            // present in the subarray with
            // negative product
            if (Neg != 0)
            {
                Neg += 1;
            }
 
            // Update res
            res = Math.Max(res, Pos);
        }
 
        // If current element is negative
        else
        {
            Pos = Pos + Neg;
            Neg = Pos - Neg;
            Neg = Pos - Neg;
 
            // Increment the length of subarray
            // with negative product
            Neg += 1;
 
            // If at least one element is present
            // in the subarray with positive product
            if (Pos != 0)
            {
                Pos += 1;
            }
 
            // Update res
            res = Math.Max(res, Pos);
        }
    }
    return res;
}
 
// Driver Code
public static void Main()
{
    int[] arr = {-1, -2, -3, 0, 1};
    int N = arr.Length;
    Console.Write(maxLenSub(arr, N));
}
}
 
// This code is contributed by Chitranayal

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

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.