Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Max / Min Stack in c++ using stl in O(1) time and space

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.
Comment

Max / Min Stack in c++ using stl in O(1) time and space

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.
Comment

PREVIOUS NEXT
Code Example
Cpp :: online c++ compiler 
Cpp :: how to implement stack 
Cpp :: c++ cout int 
Cpp :: how to pass arrays by reference c++ 
Cpp :: c++ loop vector iterator 
Cpp :: strip whitespace c++ 
Cpp :: Determine if map contains a value for a key c++ 
Cpp :: default access specifier in c++ 
Cpp :: for statement in c++ 
Cpp :: vector to char array c++ 
Cpp :: use of strtok 
Cpp :: x += c++ 
Cpp :: hello world program in c ++ using standard namespace 
Cpp :: cpp 
C :: auto click connect colab 
C :: how to remove button decoration 
C :: manifest orientation portrait 
C :: find maximum number between 3 numbers in c 
C :: sum of list in C 
C :: how to print int in c 
C :: sigaction in c 
C :: graphics in c 
C :: c iterate string 
C :: divide and conquer program in c 
C :: multiplicationin c 
C :: c print sizeof char 
C :: implicit declaration of function ‘usleep’ [-Wimplicit-function-declaration] 
C :: memcpy c 
C :: Fibonacci Series Program. in c 
C :: memory layout in c 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =