Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1 s in a binary array | Returns index of 0 to be replaced with 1 to get longest continuous sequence of 1 s . If there is no 0 in array , then it returns - 1. ; for maximum number of ; 1 around a zero for storing result ; index of previous zero ; index of previous to ; previous zero Traverse the input array ; If current element is 0 , then calculate the difference between curr and prev_prev_zero ; Update result if count of 1 s around prev_zero is more ; Update for next iteration ; Check for the last encountered zero ; Driver Code
< ? php function maxOnesIndex ( $ arr , $ n ) { $ max_count = 0 ; $ max_index ; $ prev_zero = -1 ; $ prev_prev_zero = -1 ; for ( $ curr = 0 ; $ curr < $ n ; ++ $ curr ) { if ( $ arr [ $ curr ] == 0 ) { if ( $ curr - $ prev_prev_zero > $ max_count ) { $ max_count = $ curr - $ prev_prev_zero ; $ max_index = $ prev_zero ; } $ prev_prev_zero = $ prev_zero ; $ prev_zero = $ curr ; } } if ( $ n - $ prev_prev_zero > $ max_count ) $ max_index = $ prev_zero ; return $ max_index ; } $ arr = array ( 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 1 ) ; $ n = sizeof ( $ arr ) ; echo " Index ▁ of ▁ 0 ▁ to ▁ be ▁ replaced ▁ is ▁ " , maxOnesIndex ( $ arr , $ n ) ; ? >