Fill array with 1 's using minimum iterations of filling neighbors | Returns count of iterations to fill arr [ ] with 1 s . ; Start traversing the array ; Traverse until a 0 is found ; Count contiguous 0 s ; Condition for Case 3 ; Condition to check if Case 1 satisfies : ; If count_zero is even ; If count_zero is odd ; Reset count_zero ; Case 2 ; Update res ; Driver Code
function countIterations ( arr , n ) { var oneFound = false ; var res = 0 ; for ( var i = 0 ; i < n ; ) { if ( arr [ i ] == 1 ) oneFound = true ; while ( i < n && arr [ i ] == 1 ) i ++ ; var count_zero = 0 ; while ( i < n && arr [ i ] == 0 ) { count_zero ++ ; i ++ ; } if ( oneFound == false && i == n ) return - 1 ; var curr_count ; if ( i < n && oneFound == true ) { if ( ( count_zero & 1 ) == 0 ) curr_count = count_zero / 2 ; else curr_count = ( count_zero + 1 ) / 2 ; count_zero = 0 ; } else { curr_count = count_zero ; count_zero = 0 ; } res = Math . max ( res , curr_count ) ; } return res ; } var arr = [ 0 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 ] ; document . write ( countIterations ( arr , arr . length ) ) ;