Length of longest subarray with positive product | Java program to implement the above approach ; 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
import java . util . * ; class GFG { static int maxLenSub ( int arr [ ] , int N ) { int Pos = 0 ; int Neg = 0 ; int res = 0 ; for ( int 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 = Pos + Neg ; Neg = Pos - Neg ; Neg = Pos - Neg ; Neg += 1 ; if ( Pos != 0 ) { Pos += 1 ; } res = Math . max ( res , Pos ) ; } } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { - 1 , - 2 , - 3 , 0 , 1 } ; int N = arr . length ; System . out . print ( maxLenSub ( arr , N ) ) ; } }