easy way to create a Max stack in cpp using stl:
(same idea for Min Stack)
stack<pair<int,int>> s;
insert:
/* new max will be given no. if stack is empty else we compare given no. to max at current top of stack*/
int new_max=s.empty()?given_element : max(given_element,s.top().second);
// we push the pair of given_element,new_max in s
s.push({given_element,new_max});
pop:
if (!s.smpty()){
// popped has popped number
int popped=s.top().first;
s.pop();
}
else{
// print a mesage or throw exception etc
}
max:
int maximum_elem=s.top().second;
.
.
and since all operations of stack are O(1) and .first and .second of pair is also O(1)
every operation above of Max Stack is O(1)
and we are storing just pairs of numbers so ofcourse it's O(1) space.
Code Example |
---|
Cpp :: passing a 2d array cpp |
Cpp :: if c++ |
Cpp :: c++ cout |
Cpp :: operator overload |
Cpp :: c++ function parameters |
Cpp :: sort c++ array |
Cpp :: c++ map key exists |
Cpp :: stack in c++ |
Cpp :: modify value in map c++ |
Cpp :: array list cpp |
Cpp :: in c++ |
Cpp :: c++ inline if |
Cpp :: computer vision libraries c++ |
Cpp :: cout<<"helloworld"<<endl problem |
C :: _CRT_SECURE_NO_WARNINGS |
C :: matplotlib legend remove box |
C :: print an array in c |
C :: c random list |
C :: same project on different monitor in intellij mac |
C :: c how to get an integer from user input |
C :: c static |
C :: C percentage program |
C :: add field to model rails |
C :: c assign pointer to struct |
C :: mutex c |
C :: how to modulo in c without % |
C :: c print to stderr |
C :: sleep function in c |
C :: check if string is the same c |
C :: simple bootstrap form example |