Maximum length of segments of 0’s and 1’s in C++


Problem statement

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

Example

If input string is “10111000001011” the answer will 12 as follows −

  • First segment is of length 7 10111000001011
  • Second segment is of length 5 10111000001011
  • Total length is length of (segment 1 + segment 2) = (7 + 5) = 12

Algorithm

  • If start == n then return 0.
  • Run a loop from start till n, computing for each subarray till n.
  • If character is 1 then increment the count of 1 else increment the count of 0.
  • If count of 1 is greater than 0, recursively call the function for index (k+1) i.e. next index and add the remaining length i.e. k-start+1.
  • Else only recursively call the function for next index k+1.
  • Return dp[start].

Example

 Live Demo

#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;
}

Output

When you compile and execute above program. It generates following output −

Maximum length of segment = 12

Updated on: 10-Jan-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements