Maximum Consecutive Zeroes in Concatenated Binary String in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary string of length n, another value say k is given. We have to concatenate the binary string k times. Then we have to find the maximum number of consecutive 0s in the concatenated string. Suppose binary string is “0010010”, and k = 2, then after concatenating the string k times, it will be “00100100010010”. So the maximum number of consecutive 0s is 3.

The approach is simple. If the number has all 0s, then the answer will be n * k. If the string contains ones, then the result will be either the max length of a substring of string, containing all 0s, or the sum between the length of the maximum prefix of the string containing only 0s, and the length of the maximal suffix of a string containing only 0s.

Algorithm

max_zero_count (str, n, k) −

Begin
total := 0
len := 0
for i in range 0 to n, do
   if str[i] = 0, then increase len
   else len := 0
   total := maximum of total and len
done
if total = n, then return n * k
prefix := length of maximal prefix with only 0
suffix:= length of maximal suffix with only 0
if k > 1, then
   total := max of total, and (prefix + suffix)
return total
End

Example

 Live Demo

#include <iostream>
using namespace std;
int max_length_substring(string str, int n, int k) {
   int total_len = 0;
   int len = 0;
   for (int i = 0; i < n; ++i) {
      if (str[i] == '0') //if the current character is 0, increase len
         len++;
      else
         len = 0;
      total_len = max(total_len, len);
   }
   if (total_len == n) //if the whole string has 0 only
      return n * k;
   int prefix = 0, suffix = 0;
   for (int i = 0; str[i] == '0'; ++i, ++prefix) //find length of maximal prefix with only 0;
   for (int i = n - 1; str[i] == '0'; --i, ++suffix) //find length of maximal suffix with only 0;
   if (k > 1)
      total_len = max(total_len, prefix + suffix);
   return total_len;
}
int main() {
   int k = 3;
   string str = "0010010";
   int res = max_length_substring(str, str.length(), k);
   cout << "Maximum length of 0s: " << res;
}

Output

Maximum length of 0s: 3
raja
Published on 17-Oct-2019 13:38:57
Advertisements