Tuesday, 26 Oct 2021

# Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String

Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize sum of count of consecutive 0s present at the start and end of any of the rotations of the given string S.
Examples:

Input: S = “1001”Output: 2Explanation:All possible rotations of the string are:“1001”: Count of 0s at the start = 0, at the end = 0. Sum= 0 + 0 = 0.“0011”: Count of 0s at the start = 2, at the end = 0. Sum = 2 + 0=2“0110”: Count of 0s at the start = 1, at the end = 1. Sum= 1 + 1 = 2.“1100”: Count of 0s at the start = 0, at the end = 2. Sum = 0 + 2 = 2Therefore, maximum sum possible = 2.
Input: S = “01010”Output: 2Explanation: All possible rotations of the string are:“01010”: Count of 0s at the start = 1, at the end = 1. Sum= 1+1=1“10100”: Count of 0s at the start = 0, at the end = 2. Sum= 0+2=2“01001”: Count of 0s at the start = 1, at the end = 0. Sum= 1+0=1“10010”: Count of 0s at the start = 0, at the end = 1. Sum= 0+1=1“00101”: Count of 0s at the start = 2, at the end = 0. Sum= 2+0=2Therefore, maximum sum possible = 2.

Naive Approach: The simplest idea is to generate all rotations of the given string and for each rotation, count the number of 0s present at the beginning and end of the string and calculate their sum. Finally, print the maximum sum obtained.  Below is the implementation of the above approach:

C++

#include
using namespace std;

void findMaximumZeros(string str, int n)
{

int c0 = 0;

for (int i = 0; i < n; ++i) {         if (str[i] == '0')             c0++;     }             if (c0 == n) {                     cout = i; --j) {             if (s[j] == '0')                 ce++;             else                 break;         }                     int val = cs + ce;                              mx = max(val, mx);     }             cout