Length of longest subarray with positive product | 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
function maxLenSub ( arr , N ) { var Pos = 0 ; var Neg = 0 ; var res = 0 ; for ( var 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 = Math . max ( res , Pos ) ; } else { [ Pos , Neg ] = [ Neg , Pos ] ; Neg += 1 ; if ( Pos != 0 ) { Pos += 1 ; } res = Math . max ( res , Pos ) ; } } return res ; } var arr = [ - 1 , - 2 , - 3 , 0 , 1 ] ; var N = arr . length ; document . write ( maxLenSub ( arr , N ) ) ;