[AlgoExpert] Min Max Stack Construction

Min Max Stack Construction

  • Time : O(1)
  • Space : O(n)
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
using namespace std;

// Feel free to add new properties and methods to the class.
class MinMaxStack {
vector<int> st;
vector<int> mi, ma;
public:
int peek() {
if(!st.empty()) return st.back();
return -1;
}

int pop() {
if(st.empty()) return -1;
int res = st.back();
st.pop_back();
if(mi.back() == st.size())
mi.pop_back();
if(ma.back() == st.size())
ma.pop_back();

return res;
}

void push(int number) {
st.push_back(number);
if(mi.empty() or st[mi.back()] > st.back()) {
mi.push_back(st.size() - 1);
}

if(ma.empty() or st[ma.back()] < st.back()) {
ma.push_back(st.size() - 1);
}
}

int getMin() {
if(st.empty()) return -1;
return st[mi.back()];
}

int getMax() {
if(st.empty()) return -1;
return st[ma.back()];
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/min-max-stack-construction/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.