forked from sanmitM312/InterviewPrep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minElementStack.cpp
63 lines (46 loc) · 1.08 KB
/
minElementStack.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
#include<bits/stdc++.h>
using namespace std;
class MinElemntStack{
stack<int> st;
int minElement;
public:
void push(int x){
if(st.empty()){
minElement = x;
st.push(x);
}
else{
if(x >= minElement)
st.push(x);
else{
st.push(2*x - minElement);
minElement = x;
}
}
}
bool empty() {
return st.empty();
}
int getMin() {
return minElement;
}
int top() {
return (st.top() < minElement? minElement: st.top());
}
void pop(){
if(st.top() > minElement) st.pop();
else{
int y = st.top();
minElement = 2*minElement- y;
st.pop();
}
}
};
int main(){
MinElemntStack st;
st.push(5); st.push(3); st.push(2); st.push(4); st.push(10);
while(!st.empty()){
cout << "Top : " << st.top() << " Min: " << st.getMin() << endl;
st.pop();
}
}