

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- C++ code to find minimum operations to make numbers c and d
- Program to find minimum possible maximum value after k operations in python
- Program to find minimum cost to merge stones in Python
- C++ code to find minimum time needed to do all tasks
- Minimum Cost to Merge Stones in C++
- C++ code to find maximum stones we can pick from three heaps
- C++ code to get minimum sum of cards after discarding
- C++ code to find minimal tiredness after meeting
- C++ code to find minimum arithmetic mean deviation
- Program to find minimum number of operations to move all balls to each box in Python
- Program to find maximize score after n operations in Python
- C++ code to find xth element after removing numbers
- C++ code to find tree height after n days
- Minimum move to end operations to make all strings equal in C++
- C++ code to find minimum difference between concerts durations