Maximum count of 0 s between two 1 s in given range for Q queries | Function to count the number of 0 s lying between the two 1 s for each query ; Stores count of 0 ' s ▁ that ▁ are ▁ ▁ right ▁ to ▁ the ▁ most ▁ recent ▁ 1' s ; Stores count of 0 ' s ▁ that ▁ are ▁ ▁ left ▁ to ▁ the ▁ most ▁ recent ▁ 1' s ; Stores the count of zeros in a prefix / suffix of array ; Stores the count of total 0 s ; Traverse the string S ; If current character is '1' ; Otherwise ; Update the rightBound [ i ] ; Update count and total to 0 ; Traverse the string S in reverse manner ; If current character is '1' ; Otherwise ; Update the leftBound [ i ] ; Traverse given query array ; Update the value of count ; Print the count as the result to the current query [ L , R ] ; Driver Code
function countOsBetween1s ( S , N , Q ) { let leftBound = new Array ( N ) ; let rightBound = new Array ( N ) ; let count = 0 ; let total = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' ' ) { count = total ; } else if ( S [ i ] == ' ' ) { total ++ ; } rightBound [ i ] = count ; } count = 0 ; total = 0 ; for ( let i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == ' ' ) { count = total ; } else if ( S [ i ] == ' ' ) { total ++ ; } leftBound [ i ] = count ; } for ( let q = 0 ; q < 2 ; q ++ ) { let L = Q [ q ] [ 0 ] ; let R = Q [ q ] [ 1 ] ; count = leftBound [ L ] + rightBound [ R ] - total ; document . write ( count + " " ) ; } } let S = " " ; let Q = [ [ 0 , 4 ] , [ 0 , 5 ] ] ; let N = S . length ; countOsBetween1s ( S , N , Q ) ;