File tree 2 files changed +78
-0
lines changed
2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < stack>
3
+ #include < vector>
4
+ using namespace std ;
5
+ // more optimized approach
6
+
7
+ class MinStack
8
+ {
9
+ public:
10
+ stack<long long int > s; // val , minVal
11
+ long long int minVal;
12
+
13
+ MinStack () {} // default constructor
14
+
15
+ void push (int val)
16
+ {
17
+ if (s.empty ())
18
+ {
19
+ s.push (val);
20
+ minVal = val;
21
+ }
22
+ else
23
+ {
24
+ if (val < minVal)
25
+ {
26
+ s.push ((long long )2 * val - minVal);
27
+ minVal = val;
28
+ }
29
+ else
30
+ {
31
+ s.push (val);
32
+ }
33
+ }
34
+ }
35
+
36
+ void pop ()
37
+ {
38
+ if (s.top () < minVal)
39
+ {
40
+ minVal = 2 * minVal - s.top ();
41
+ }
42
+
43
+ s.pop ();
44
+ }
45
+
46
+ int top ()
47
+ {
48
+ if (s.top () < minVal)
49
+ {
50
+ return minVal;
51
+ }
52
+
53
+ return s.top ();
54
+ }
55
+
56
+ int getMin ()
57
+ {
58
+ return minVal;
59
+ }
60
+ };
61
+
62
+ int main ()
63
+ {
64
+ MinStack ms;
65
+
66
+ ms.push (-2 );
67
+ ms.push (0 );
68
+ ms.push (-3 );
69
+
70
+ cout << " Minimum value : " << ms.getMin () << endl;
71
+
72
+ ms.pop ();
73
+
74
+ cout << " Top value : " << ms.top () << endl;
75
+ cout << " Minimum value : " << ms.getMin () << endl;
76
+
77
+ return 0 ;
78
+ }
You can’t perform that action at this time.
0 commit comments