Length of longest subarray with positive product

16 Nov, 2021
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: 3Explanation:The longest subarray with positive products is: {1, -2, -3}. Therefore, the required length is 3.
Input: arr[]={-1, -2, 0, 1, 2}Output: 2Explanation: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:
Initialize the variable, say res, to store the length of the longest subarray with the positive product.Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively.Iterate over the array.If arr[i] = 0: Reset the value of Pos and Neg.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.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.Update res=max(res, Pos).
Initialize the variable, say res, to store the length of the longest subarray with the positive product.
Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively.
Iterate over the array.
If arr[i] = 0: Reset the value of Pos and Neg.
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.
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.
Update res=max(res, Pos).
C++
Python3
Java
C#
Javascript
// 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 positiveint 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 Codeint main(){    int arr[] = { -1, -2, -3, 0, 1 };    int N = sizeof(arr) / sizeof(arr[0]);    cout << maxLenSub(arr, N);}
# Python3 program to implement# the above approach # Function to find the length of# longest subarray whose product# is positivedef 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 Codeif __name__ == '__main__':         arr = [ -1, -2, -3, 0, 1 ]    N = len(arr)         print(maxLenSub(arr, N)) # This code is contributed by mohit kumar 29
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the length of// longest subarray whose product// is positivestatic 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;            Pos = 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 Codepublic 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
// C# program to implement// the above approachusing System;class GFG{ // Function to find the length of// longest subarray whose product// is positivestatic 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;            Pos = 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 Codepublic 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
<script> // JavaScript program to implement// the above approach // Function to find the length of// longest subarray whose product// is positivefunction maxLenSub(arr, N){    // Stores the length of current    // subarray with positive product    var Pos = 0;     // Stores the length of current    // subarray with negative product    var Neg = 0;     // Stores the length of the longest    // subarray with positive product    var res = 0;     for (var 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, 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 = Math.max(res, Pos);        }    }    return res;} // Driver Codevar arr = [-1, -2, -3, 0, 1];var N = arr.length;document.write( maxLenSub(arr, N));  </script>
2
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
Rajput-Ji
ukasp
noob2000
anmolsharma283
subarray
Arrays
Dynamic Programming
Mathematical
Searching
Arrays
Searching
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
What is Data Structure: Types, Classifications and Applications
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Longest Palindromic Substring | Set 1
Longest Increasing Subsequence | DP-3