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
def maxLenSub ( arr , N ) : NEW_LINE INDENT Pos = 0 NEW_LINE Neg = 0 NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT Pos = Neg = 0 NEW_LINE DEDENT elif ( arr [ i ] > 0 ) : NEW_LINE INDENT Pos += 1 NEW_LINE if ( Neg != 0 ) : NEW_LINE INDENT Neg += 1 NEW_LINE DEDENT res = max ( res , Pos ) NEW_LINE DEDENT else : NEW_LINE INDENT Pos , Neg = Neg , Pos NEW_LINE Neg += 1 NEW_LINE if ( Pos != 0 ) : NEW_LINE INDENT Pos += 1 NEW_LINE DEDENT res = max ( res , Pos ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 1 , - 2 , - 3 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxLenSub ( arr , N ) ) NEW_LINE DEDENT