Fill array with 1 's using minimum iterations of filling neighbors | C ++ program to find number of iterations to fill with all 1 s ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countIterations ( int arr [ ] , int n ) { bool oneFound = false ; int res = 0 ; for ( int i = 0 ; i < n ; ) { if ( arr [ i ] == 1 ) oneFound = true ; while ( i < n && arr [ i ] == 1 ) i ++ ; int count_zero = 0 ; while ( i < n && arr [ i ] == 0 ) { count_zero ++ ; i ++ ; } if ( oneFound == false && i == n ) return -1 ; int 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 = max ( res , curr_count ) ; } return res ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countIterations ( arr , n ) ; return 0 ; }