Maximum number of removals of given subsequence from a string in C++


Given the task is to find the maximum number of removals of given subsequence from a string. A string s is given and we have to find the maximum number of subsequence ‘abc’ that can be removed from the string.

Let’s now understand what we have to do using an example:

Input

s = ‘dnabcxy’

Output

1

Explanation − Only one subsequence of ‘abc’ can be found in the given string (‘dnabcxy’), therefore the output is 1.

Input

s = ‘zcabcxabc’

Output

2 (‘zcabcxabc’)

Approach used in the below program as follows

  • In Max() function initialize variables i, a, ab, abc with value = 0 and of type int.

  • Loop from i=0 till I < s.length()

  • Inside the loop check if (s[i] == ‘a’), if so then increment value of a.

  • Else, check if (s[i] == ‘b’), if true then again check if (a > 0). If both conditions are true then decrease value of a by 1 and increment the value of ab.

  • Finally, check if (s[i] == ‘c’), if true then again check if (ab > 0). If both conditions are true then decrease value of ab by 1 and increment the value of abc.

  • Return abc

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int Max(string s){
   int i=0, a=0, ab=0, abc=0;
   for (i = 0; i < s.length(); i++){
      if (s[i] == 'a'){
         a++;
      }
      else if (s[i] == 'b'){
         if (a > 0){
            a--;
            ab++;
         }
      }
      else if (s[i] == 'c'){
         if (ab > 0){
            ab--;
            abc++;
         }
      }
   }
   return abc;
}
//main function
int main(){
   string s = "zcabcxabc";
   cout << Max(s);
   return 0;
}

Output

2

Updated on: 03-Aug-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements