Saturday, November 16, 2024
Google search engine
HomeLanguagesDynamic ProgrammingLength of longest subarray with positive product

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++




// 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);
}


Python3




# 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


Java




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


C#




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


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to find the length of
// longest subarray whose product
// is positive
function 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 Code
var arr = [-1, -2, -3, 0, 1];
var N = arr.length;
document.write( maxLenSub(arr, N));
 
 
</script>


Output: 

2

Time Complexity: O(N)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments