Query to find length of the longest subarray consisting only of 1 s | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 = max ( maxlength , sum ) ; } return maxlength ; } void solveQueries ( int arr [ ] , int n , vector < vector < int > > Q , int k ) { int cntQuery = Q . size ( ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { cout << longestsubarray ( arr , n ) << " ▁ " ; } else { arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 ; } } } int main ( ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; vector < vector < int > > Q = { { 1 } , { 2 , 3 } , { 1 } } ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; }