Std :: stack <int> with maximum function?
3 answers
The idea would be to track the maximum length using pairs on the stack. If you push something onto the stack, you update max accordingly.
class Stack {
private:
stack<pair<int,int>> s;
public:
bool empty() const {
return s.empty();
}
int max() const {
assert (empty() == false);
return s.top().second;
}
int pop() {
int ans = s.top().first;
s.pop();
return ans;
}
void push(int x) {
if (s.empty() || x > s.top().second)
{
s.emplace(x, x);
}
else
{
s.emplace(x, s.top().second);
}
}
};
+6