- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# 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 Articles
- C++ code to find minimum operations to make numbers c and d
- Program to find minimum possible maximum value after k operations in python
- C++ code to find minimum time needed to do all tasks
- Program to find minimum cost to merge stones in Python
- C++ code to get minimum sum of cards after discarding
- Minimum Cost to Merge Stones in C++
- C++ code to find maximum stones we can pick from three heaps
- Program to find minimum number of operations to move all balls to each box in Python
- Minimum move to end operations to make all strings equal in C++
- Pain Remains After Passing Kidney Stones
- C++ code to find minimum arithmetic mean deviation
- Minimum delete operations to make all elements of array same in C++.
- Minimum operations required to make all the array elements equal in C++
- Minimum operations required to set all elements of binary matrix in C++
- C++ code to find minimal tiredness after meeting