Length of longest subarray with positive product | C ++ program to implement the above approach ; Function to find the length of longest subarray whose product is positive ; Stores the length of current subarray with positive product ; Stores the length of current subarray with negative product ; Stores the length of the longest subarray with positive product ; Reset the value ; If current element is positive ; Increment the length of subarray with positive product ; If at least one element is present in the subarray with negative product ; Update res ; If current element is negative ; Increment the length of subarray with negative product ; If at least one element is present in the subarray with positive product ; Update res ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLenSub ( int arr [ ] , int N ) { int Pos = 0 ; int Neg = 0 ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { Pos = Neg = 0 ; } else if ( arr [ i ] > 0 ) { Pos += 1 ; if ( Neg != 0 ) { Neg += 1 ; } res = max ( res , Pos ) ; } else { swap ( Pos , Neg ) ; Neg += 1 ; if ( Pos != 0 ) { Pos += 1 ; } res = max ( res , Pos ) ; } } return res ; } int main ( ) { int arr [ ] = { -1 , -2 , -3 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLenSub ( arr , N ) ; }