-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin_Stack.cpp
85 lines (77 loc) · 1.32 KB
/
Min_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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//Get Minimum Element from stack every time..O(1) time and O(1) space;;
//Idea---> We will be storing elemenents in stack always minimun ..and keeping the current minimum in minElem..Let say an elemt come
// whcih is less than minELem..i.e now we will push 2*x - minElem in the stack..and update the minElem..As 2*x-minELem is alwasy less tham
// x and whe we are poping elements and we found an elemnent less than minElem we found there is some analomy..So Thats how this
// this logic works..
#include<bits/stdc++.h>
using namespace std;
#define boost ios_base::sync_with_stdio(false); cin.tie(NULL);
stack<long long int> stk;
int minElem = INT_MAX;
void _push(long long int x)
{
if(x>minElem)
{
stk.push(x);
}
else
{
stk.push(2*x - minElem);
minElem = x;
}
}
void _pop()
{
if(stk.empty())
{
cout << "Nothing to pop\n";
}
else
{
if(stk.top()<minElem)
{
minElem = 2*minElem - stk.top();
}
stk.pop();
}
}
int _getMin()
{
if(stk.empty())
{
return INT_MIN;
}
else
{
return minElem;
}
}
int _seek()
{
if(stk.empty())
{
return 0;
}
else
{
if(stk.top()>minElem)
{
return stk.top();
}
else
{
return 2*minElem - stk.top();
}
}
}
int main()
{
boost;
_push(-2);
_push(0);
_push(-3);
cout << _getMin() << "\n";
_pop();
cout << _seek() << "\n";
cout << _getMin() << "\n";
}