Longest substring of 0 s in a string formed by k concatenations | Function to calculate maximum length of substring containing only zero ; loop to first calculate longest substring in string ; if all elements in string are '0' ; Else , find size of prefix and suffix containing only zeroes ; Calculate prefix containing only zeroes ; Calculate suffix containing only zeroes ; if k <= 1 then there is no need to take prefix + suffix into account ; Driver code
< ? php function subzero ( $ str , $ k ) { $ ans = 0 ; $ curr = 0 ; $ len = strlen ( $ str ) ; for ( $ i = 0 ; $ i < $ len ; ++ $ i ) { if ( $ str [ $ i ] == '0' ) $ curr ++ ; else $ curr = 0 ; $ ans = max ( $ ans , $ curr ) ; } if ( $ ans == $ len ) return $ len * $ k ; else { $ pre = 0 ; $ suff = 0 ; for ( $ i = 0 ; $ i < $ len ; $ i ++ ) { if ( $ str [ $ i ] == '0' ) $ pre ++ ; else break ; } for ( $ i = $ len - 1 ; $ i >= 0 ; $ i -- ) { if ( $ str [ $ i ] == '0' ) $ suff ++ ; else break ; } if ( $ k > 1 ) $ ans = max ( $ ans , $ pre + $ suff ) ; return $ ans ; } } $ str = "00100110" ; $ k = 5 ; echo subzero ( $ str , $ k ) ; ? >