Length of longest subarray with product greater than or equal to 0 | C ++ implementation of the above approach ; Function that count the length of longest subarray with product greater than or equals to zero ; If product is greater than zero , return array size ; Traverse the array and if any negative element found then update the length of longest subarray with the length of left and right subarray ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( int arr [ ] , int N ) { int product = 1 , len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { product *= arr [ i ] ; } if ( product >= 0 ) { return N ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { len = max ( len , max ( N - i - 1 , i ) ) ; } } return len ; } int main ( ) { int arr [ ] = { -1 , 1 , 1 , -2 , 3 , 2 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLength ( arr , N ) << endl ; return 0 ; }