-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_api_getMax_variant1.cpp
56 lines (48 loc) · 1.01 KB
/
stack_api_getMax_variant1.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
//getMax in O(1) time
//https://ide.geeksforgeeks.org/iUUxktagqh
#include<bits/stdc++.h>
using namespace std;
struct MaxStack{
stack<int> myst;
int maxEle;
void Top(){
if(!myst.empty()){
int t = myst.top();
cout<<"Top ele is:- ";
(t>maxEle)?cout<<maxEle:cout<<t;
}
}
void Push(int x){
if(myst.empty()){ myst.push(x); maxEle = x;}
else{
if(x>=maxEle){
myst.push(2*x - maxEle);
maxEle = x;
}
}
}
void Pop(){
if(myst.empty()){
cout<<"Empty stack"<<"\n";
return;
}
int top = myst.top();
myst.pop();
if(top >= maxEle){
cout<<maxEle<<"\n";
maxEle = 2*maxEle - top;
}
else
cout<<top<<"\n";
}
};
int main(){
MaxStack x;
x.Push(10);
x.Push(20);
x.Push(30);
x.Push(40);
x.Pop();
x.Push(42);
x.Top();
}