# Minimize count of 0s required to be removed to maximize length of longest substring of 1s

In this article, we will delve into an intriguing problem that involves string manipulation in C++. The problem we're examining today is how to "Minimize the count of 0s required to be removed to maximize the length of the longest substring of 1s". This problem is a great way to hone your skills in string manipulation and dynamic programming.

## Problem Statement

Given a binary string, the task is to minimize the count of 0s required to be removed in order to maximize the length of the longest substring of 1s.

## C++ Solution Approach

To solve this problem, we can use a sliding window approach. We'll maintain two pointers, left and right. Initially, both pointers point to the first element. Then, we'll keep moving the right pointer to the right. If we encounter a '0', we increment a counter. If the counter becomes larger than the number of allowed zero removals, we move the left pointer to the right until we encounter a '0' and decrement the counter.

We'll also maintain a variable maxLen to store the maximum length of the substring of 1s we've seen so far.

### Example

Here's the C++ code that solves the problem −

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int maxSubstring(string str, int k) {
int zeroCount = 0;
int left = 0;
int maxLen = 0;

for (int right = 0; right < str.size(); right++) {
if (str[right] == '0') {
zeroCount++;
}
while (zeroCount > k) {
if (str[left] == '0') {
zeroCount--;
}
left++;
}
maxLen = max(maxLen, right - left + 1);
}
return maxLen;
}

int main() {
string str = "110100110";
int k = 2; // number of zeros that can be removed
int result = maxSubstring(str, k);
cout << "The maximum length of the substring of 1s is: " << result << endl;
return 0;
}


### Output

The maximum length of the substring of 1s is: 5


## Explanation with a Test Case

Let's take the binary string "110100110" and we're allowed to remove 2 zeros.

When we pass this string and the value of k to the maxSubstring function, it starts scanning from the left. Every time it encounters a '0', it increments the zeroCount. When zeroCount exceeds k, it starts moving the left pointer right until it encounters a '0' and decrements the zeroCount.

During this process, it keeps updating maxLen which is the maximum length of the substring of 1s. For the given string, the maximum length of the substring of 1s after removing at most 2 zeros is 5, which is the substring "11111" after removing the second and third '0'.

So, the function will return 5.

## Conclusion

This problem demonstrates how the sliding window technique can be effectively used for solving complex string manipulation problems in C++. It's an excellent problem for understanding and practicing dynamic programming and string handling techniques. Keep practicing such problems to enhance your coding skills in C++.

Updated on: 18-May-2023

28 Views 