-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathday-10.cpp
38 lines (32 loc) · 810 Bytes
/
day-10.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
/*
Question: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
*/
class MinStack {
public:
stack<pair<int, int>> tinyStack;
int min;
MinStack() {
min = INT_MAX;
}
void push(int x) {
if (x < min) min = x;
tinyStack.push(make_pair(x, min));
}
void pop() {
tinyStack.pop();
if (tinyStack.size() == 0)
min = INT_MAX;
else
min = tinyStack.top().second;
}
int top() {
return tinyStack.top().first;
}
int getMin() {
return tinyStack.top().second;
}
};