C++ code to find minimum stones after all operations


Suppose we have a string S with n characters. The characters will be either '+' or '-'. There is a pile of stones, n times we either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile. We have to find the minimal possible number of stones that can be in the pile after making these operations. If we took the stone on i-th operation, S[i] is equal to "-", if added, S[i] is equal to "+".

So, if the input is like S = "++-++", then the output will be 3. If we had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.

Steps

To solve this, we will follow these steps −

n := size of S
for initialize i := 0, when i < n, update (increase i by 1), do:
   res := (if S[i] is same as '-', then maximum of res - 1 and 0,
otherwise res + 1)
return res

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(), res = 0;
   for (int i = 0; i < n; i++)
      res = (S[i] == '-') ? max(res - 1, 0) : res + 1;
   return res;
}
int main(){
   string S = "++-++";
   cout << solve(S) << endl;
}

Input

"++-++"

Output

3

Updated on: 29-Mar-2022

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements