Query to find length of the longest subarray consisting only of 1 s | Java Program for the above approach ; Function to calculate the longest subarray consisting of 1 s only ; Stores the maximum length of subarray containing 1 s only ; Traverse the array ; If current element is '1' ; Increment length ; Otherwise ; Reset length ; Update maximum subarray length ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries
import java . util . * ; public class Main { static int longestsubarray ( int a [ ] , int N ) { int maxlength = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 1 ) { sum ++ ; } else { sum = 0 ; } maxlength = Math . max ( maxlength , sum ) ; } return maxlength ; } static void solveQueries ( int arr [ ] , int n , Vector < Vector < Integer > > Q , int k ) { int cntQuery = Q . size ( ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q . get ( i ) . get ( 0 ) == 1 ) { System . out . print ( longestsubarray ( arr , n ) + " ▁ " ) ; } else { arr [ Q . get ( i ) . get ( 1 ) - 1 ] ^= 1 ; } } } public static void main ( String [ ] args ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; Vector < Vector < Integer > > Q = new Vector < Vector < Integer > > ( ) ; Vector < Integer > v1 = new Vector < Integer > ( ) ; Vector < Integer > v2 = new Vector < Integer > ( ) ; Vector < Integer > v3 = new Vector < Integer > ( ) ; v1 . add ( 1 ) ; v2 . add ( 2 ) ; v2 . add ( 3 ) ; v3 . add ( 1 ) ; Q . add ( v1 ) ; Q . add ( v2 ) ; Q . add ( v3 ) ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; } }