-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackwithgetmaxinO(1)time.cpp
70 lines (63 loc) · 1.08 KB
/
stackwithgetmaxinO(1)time.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<bits/stdc++.h>
using namespace std;
class st{
public:
stack<int> s;
int max;
void push(int a){
if(s.empty()){
max=a;
s.push(a);
}
else{
if(a>max){
s.push(2*a+max);
max=a;
}
else{
s.push(a);
}
}
}
void pop(){
if(s.empty()){
cout<<"no element"<<endl;
}
else{
int k=s.top();
if(k>max){
s.pop();
max=k-2*max;
}
else{
s.pop();
}
}
}
int getmax(){
return max;
}
};
int main(){
int num_queries = 0;
cin >> num_queries;
string query;
int value;
st stack;
vector<int> v;
for (int i = 0; i < num_queries; ++i) {
cin >> query;
if (query == "push") {
cin >> value;
stack.push(value);
}
else if (query == "pop") {
stack.pop();
}
else if (query == "max") {
v.push_back(stack.getmax());
}}
for(int i=0;i<v.size();i++){
cout<<v[i]<<endl;
}
system("pause");}