forked from anupam-kumar-krishnan/Competitive_Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minimum Stack.cpp
57 lines (53 loc) · 884 Bytes
/
Minimum Stack.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
class MinimumStack
{
public:
stack<int> s;
int mini;
MinimumStack()
{
mini = -1;
}
void append(int val)
{
if (s.empty() || mini == -1)
{
s.push(val);
mini = val;
}
else if (val < mini)
{
s.push(2 * val - mini);
mini = val;
}
else
{
s.push(val);
}
}
int peek()
{
if (s.top() < mini)
{
return mini;
}
return s.top();
}
int min()
{
return mini;
}
int pop()
{
if (s.top() < mini)
{
int k = 2 * mini - s.top();
s.pop();
int ret = mini;
mini = k;
return ret;
}
int a = s.top();
s.pop();
return a;
}
};