Length of second longest sequence of consecutive 1 s in a binary array | Java implementation of the above approach ; Function to find maximum and second maximum length ; Initialise maximum length ; Initialise second maximum length ; Initialise count ; Iterate over the array ; If sequence ends ; Reset count ; Otherwise ; Increase length of current sequence ; Update maximum ; Traverse the given array ; If sequence continues ; Increase length of current sequence ; Update second max ; Reset count when 0 is found ; Print the result ; Driver code ; Given array ; Function Call
import java . io . * ; import java . util . * ; class GFG { static void FindMax ( int arr [ ] , int N ) { int maxi = - 1 ; int maxi2 = - 1 ; int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( arr [ i ] == 0 ) count = 0 ; else { count ++ ; maxi = Math . max ( maxi , count ) ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) { count ++ ; if ( count > maxi2 && count < maxi ) { maxi2 = count ; } } if ( arr [ i ] == 0 ) count = 0 ; } maxi = Math . max ( maxi , 0 ) ; maxi2 = Math . max ( maxi2 , 0 ) ; System . out . println ( maxi2 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int n = arr . length ; FindMax ( arr , n ) ; } }