-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetmin()_stack.cpp
More file actions
112 lines (96 loc) · 2.11 KB
/
Copy pathGetmin()_stack.cpp
File metadata and controls
112 lines (96 loc) · 2.11 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
GFG
love babbar approach :--
#include<stack>
#include<limits.h>
class SpecialStack {
// Define the data members.
stack<int> s;
int mini = INT_MAX;
/*----------------- Public Functions of SpecialStack -----------------*/
public:
void push(int data) {
//for first element
if(s.empty()) {
s.push(data);
mini = data;
}
else
{
if(data < mini) {
s.push(2*data - mini);
mini = data;
}
else
{
s.push(data);
}
}
}
int pop() {
if(s.empty()){
return -1;
}
int curr = s.top();
s.pop();
if(curr > mini) {
return curr;
}
else
{
int prevMin = mini;
int val = 2*mini - curr;
mini = val;
return prevMin;
}
}
int top() {
if(s.empty())
return -1;
int curr = s.top();
if(curr < mini) {
return mini;
}
else
{
return curr;
}
}
bool isEmpty() {
return s.empty();
}
int getMin() {
if(s.empty())
return -1;
return mini;
}
};
ANother Approach
int minEle;
stack<int> s;
public:
/*returns min element from stack*/
int getMin(){
if(s.empty())return -1;
return minEle;
//Write your code here
}
/*returns poped element from stack*/
int pop(){
if(s.empty())return -1;
int t=s.top();s.pop();
if(t>=0)return t+minEle;
else{
int x=minEle;
minEle=minEle-t;
return x;
}
//Write your code here
}
/*push element x into the stack*/
void push(int x){
if(s.empty())minEle=x;
int t=x-minEle;
s.push(t);
minEle=min(minEle,x);
//Write your code here
}