Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Max 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 :: opengl triangle example 
Cpp :: c++ convert const char* to LPCWSTR 
Cpp :: what is c++ function 
Cpp :: turn github into vscode 
Cpp :: c++ is nan 
Cpp :: converter c++ to c 
Cpp :: how to code a segment tree in c++ 
Cpp :: if statement in c++ 
Cpp :: C++ Area and Circumference of a Circle 
Cpp :: stream in c++ 
Cpp :: C++ Assignment Operators 
Cpp :: c++ press any key 
Cpp :: c++ function with parameters 
Cpp :: un aliment traduction espagnol 
C :: colourful text in c 
C :: what is meaning of product *= in c 
C :: c remove last character from a string 
C :: como programar a area de um triangulo em c 
C :: C float division 
C :: bootstrap 5 modal not working vue js 3 
C :: Prime Number Check Program in C 
C :: fast inverse square root explained 
C :: c printf uint32_t 
C :: selection sort in c 
C :: C read a character 
C :: how to modulo in c without use the operator 
C :: gcc option to show rules of makefile 
C :: c programming how to force stop the programme 
C :: struct main function c in unix 
C :: Bootstrap textarea from 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =