Given a string comprising of ones and zeros. The task is to find the maximum length of the segments of string such that a number of 1 in each segment is greater than 0
If input string is “10111000001011” the answer will 12 as follows −
#include <bits/stdc++.h> using namespace std; int getSegmentWithMaxLength(int start, string str, int n, int dp[]) { if (start == n) { return 0; } if (dp[start] != -1) { return dp[start]; } dp[start] = 0; int one = 0; int zero = 0; int k; for (k = start; k < n; ++k) { if (str[k] == '1') { ++one; } else { ++zero; } if (one > zero) { dp[start] = max(dp[start], getSegmentWithMaxLength(k + 1, str, n, dp) + k - start + 1); } else { dp[start] = max(dp[start], getSegmentWithMaxLength(k + 1, str, n, dp)); } } return dp[start]; } int main() { string str = "10111000001011"; int n = str.size(); int dp[n + 1]; memset(dp, -1, sizeof(dp)); cout << "Maximum length of segment = " << getSegmentWithMaxLength(0, str, n, dp) << endl; return 0; }
When you compile and execute above program. It generates following output −
Maximum length of segment = 12