Longest substring of 0 s in a string formed by k concatenations | C ++ code to find maximum length of substring that contains only 0 's ; 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 ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int subzero ( string str , int k ) { int ans = 0 , curr = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str [ i ] == '0' ) curr ++ ; else curr = 0 ; ans = max ( ans , curr ) ; } if ( ans == len ) return len * k ; else { int pre = 0 , suff = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) pre ++ ; else break ; } for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' ) suff ++ ; else break ; } if ( k > 1 ) ans = max ( ans , pre + suff ) ; return ans ; } } int main ( ) { string str = "00100110" ; int k = 5 ; cout << subzero ( str , k ) ; return 0 ; }