C++ program to count minimum how many minutes after there will be no new angry students

C++Server Side ProgrammingProgramming

Suppose we have a string S of length n, with only two types of characters, 'A' or 'P'. There are n students in a row, the ith student is angry if S[i] = 'A', if it is 'P' it says S[i] is patient. An angry student at index i will hit patient student in index i+1 in every minute, and for the last student even it he is angry, he cannot hit anyone. After hitting a patient student, that student also gets angry. We have to find the minimum minutes for after that no new students get angry.

So, if the input is like S = "PPAPP", then the output will be 2, because after first minute, the string will be "PPAAP", then in second minute "PPAAA", then no new student gets angry again.

Steps

To solve this, we will follow these steps −

n := size of S
ans := 0, cnt = 0
for initialize i := n - 1, when i >= 0, update (decrease i by 1), do:
   if S[i] is same as 'P', then:
      (increase cnt by 1)
   Otherwise
      ans := maximum of ans and cnt
      cnt := 0
return ans

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(string S) {
   int n = S.size();
   int ans = 0, cnt = 0;
   for (int i = n - 1; i >= 0; i--) {
      if (S[i] == 'P') {
         cnt++;
      } else {
         ans = max(ans, cnt);
         cnt = 0;
      }
   }
   return ans;
}
int main() {
   string S = "PPAPP";
   cout << solve(S) << endl;
}

Input

PPAPP

Output

2
raja
Updated on 03-Mar-2022 11:37:58

Advertisements