Skip to content

Commit f041e3f

Browse files
authored
Merge pull request #1165 from akshaymagar2003/main
Created Stack with max API
2 parents fba3db4 + 765f363 commit f041e3f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Stacks/Stack_with_max_API.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Time Complexity of all Operations is O(1)
3+
Space Complexity is O(n)
4+
In this implementation, we use two stacks: s is the main stack that holds the elements of the stack, and max_s is a secondary stack that holds the maximum values in s. When a new value is pushed onto the stack, we compare it with the current maximum value in max_s and add it to max_s if it's greater than or equal to the current maximum.
5+
*/
6+
#include <stack>
7+
using namespace std;
8+
9+
class MaxStack {
10+
private:
11+
stack<int> s; // Main stack that holds the elements of the stack
12+
stack<int> max_s; // Secondary stack that holds the maximum values in s
13+
14+
public:
15+
void push(int val) {
16+
s.push(val); // Push the value onto the main stack
17+
if (max_s.empty() || val >= max_s.top()) {
18+
// If max_s is empty or the new value is greater than or equal to the current maximum,
19+
// push the value onto max_s
20+
max_s.push(val);
21+
}
22+
}
23+
24+
void pop() {
25+
if (s.top() == max_s.top()) {
26+
// If the top value of s is equal to the top value of max_s, it means that the top value
27+
// of s is the current maximum, so we need to pop it from max_s as well
28+
max_s.pop();
29+
}
30+
s.pop(); // Pop the value from the main stack
31+
}
32+
33+
int top() {
34+
return s.top(); // Return the top value of the main stack
35+
}
36+
37+
int max() {
38+
return max_s.top(); // Return the top value of max_s, which is the maximum value in the stack
39+
}
40+
41+
bool empty() {
42+
return s.empty(); // Check if the main stack is empty
43+
}
44+
};

0 commit comments

Comments
 (0)