Length of maximum product subarray | C ++ program to find maximum length subarray having non zero product ; Function that returns the maximum length subarray having non zero product ; zeroindex list to store indexex of zero ; If zeroindex list is empty then Maxlength is as size of array ; If zeroindex list is not empty ; first zero is on index 2 that means two numbers positive , before index 2 so as their product is positive to ; Checking for other indexex ; If the difference is greater than maxlen then maxlen is updated ; To check the length of remaining array after last zeroindex ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Maxlength ( int arr [ ] , int N ) { vector < int > zeroindex ; int maxlen ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) zeroindex . push_back ( i ) ; } if ( zeroindex . size ( ) == 0 ) { maxlen = N ; } else { maxlen = zeroindex [ 0 ] ; for ( int i = 0 ; i < zeroindex . size ( ) - 1 ; i ++ ) { if ( zeroindex [ i + 1 ] - zeroindex [ i ] - 1 > maxlen ) { maxlen = zeroindex [ i + 1 ] - zeroindex [ i ] - 1 ; } } if ( N - zeroindex [ zeroindex . size ( ) - 1 ] - 1 > maxlen ) { maxlen = N - zeroindex [ zeroindex . size ( ) - 1 ] - 1 ; } } cout << maxlen << endl ; } int main ( ) { int N = 9 ; int arr [ ] = { 7 , 1 , 0 , 1 , 2 , 0 , 9 , 2 , 1 } ; Maxlength ( arr , N ) ; }