-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathMinStack.cpp
More file actions
42 lines (33 loc) · 784 Bytes
/
MinStack.cpp
File metadata and controls
42 lines (33 loc) · 784 Bytes
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
// This is the solution for Min Stack question from Leetcode
// https://leetcode.com/problems/min-stack/description/
class MinStack {
stack<long> st;
int minElement= INT_MAX;
public:
MinStack() {}
void push(int val) {
if(val< minElement){
st.push(2ll*val - minElement);
minElement= val;
}else{
st.push(val);
}
}
void pop() {
if(st.empty())
return;
if(st.top()<minElement){
minElement= 2ll*minElement - st.top();
}
st.pop();
}
int top() {
if(st.top()<minElement){
return minElement;
}
return st.top();
}
int getMin() {
return minElement;
}
};