Length of maximum product subarray | 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
function Maxlength ( arr , N ) { let zeroindex = Array . from ( { length : 20000 } , ( _ , i ) => 0 ) ; let maxlen ; let size = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) zeroindex [ size ++ ] = i ; } if ( size == 0 ) { maxlen = N ; } else { maxlen = zeroindex [ 0 ] ; for ( let i = 0 ; i < size ; i ++ ) { if ( zeroindex [ i + 1 ] - zeroindex [ i ] - 1 > maxlen ) { maxlen = zeroindex [ i + 1 ] - zeroindex [ i ] - 1 ; } } if ( N - zeroindex [ size - 1 ] - 1 > maxlen ) { maxlen = N - zeroindex [ size - 1 ] - 1 ; } } document . write ( maxlen ) ; } let N = 9 ; let arr = [ 7 , 1 , 0 , 1 , 2 , 0 , 9 , 2 , 1 ] ; Maxlength ( arr , N ) ;