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:
- 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++
// 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
# 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
// 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#
// 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 |
Javascript
<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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
