Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Min Stack

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 :: how to initialize a vector in c++ 
Cpp :: c++ get last element in array 
Cpp :: double pointers C++ 
Cpp :: assignment operator 
Cpp :: random c++ 
Cpp :: c++ sudoku solver 
Cpp :: middle node of linked list 
Cpp :: function prototype c++ 
Cpp :: program to find third smallest number c++ 
Cpp :: loop in c++ 
Cpp :: Find first and last digit of int 
Cpp :: passare un array a una funzione 
Cpp :: print all even number using for loop c++ 
Cpp :: 2927260.eps 2927262.jpg 2927263.ai License free.txt License premium.txt 
C :: hello word c 
C :: swapping of two numbers in c without temporary variable 
C :: pygame detect click 
C :: arma 3 get group size 
C :: bubble sort a linked list in c 
C :: find power of a number in c 
C :: c get random float 
C :: libdvd-pkg: `apt-get check` failed 
C :: unity set transform position code 
C :: matplotlib plot circle marker 
C :: right side of div 
C :: downgrade chrome to previous stable version in linux 
C :: text berjalan html 
C :: format specifiers in c 
C :: search in gz file 
C :: form controls in bootsrap 
ADD CONTENT
Topic
Content
Source link
Name
5+7 =