Max Stack - CPP Solution

1. Introduction

This blog post focuses on designing a Max Stack data structure, which is an advanced version of a regular stack that allows retrieving the maximum element in the stack in constant time.


Design a Max Stack data structure that supports pushing, popping, top (retrieving the top element), and retrieving the maximum element in the stack. All operations should be done in O(1) time complexity.

2. Solution Steps

1. Use two stacks: one to store the actual stack elements (mainStack) and another to store the maximum elements (maxStack).

2. When pushing an element, add it to mainStack and update maxStack if the element is greater than the current maximum.

3. When popping, remove the element from both stacks if it's equal to the current maximum.

4. The top operation returns the top of mainStack.

5. The getMax operation returns the top of maxStack.

3. Code Program

#include <iostream>
#include <stack>
using namespace std;

class MaxStack {
    stack<int> mainStack, maxStack;

    // Push element onto stack
    void push(int x) {
        if (maxStack.empty() || x >= {

    // Remove the element on top of the stack
    void pop() {
        if ( == {

    // Get the top element
    int top() {

    // Retrieve the maximum element
    int getMax() {

// Function to demonstrate the usage of MaxStack
void testMaxStack() {
    MaxStack stack;
    cout << "Current Max: " << stack.getMax() << endl;
    cout << "Current Max after popping: " << stack.getMax() << endl;

int main() {
    return 0;


Current Max: 8
Current Max after popping: 4


The MaxStack class uses two stacks for efficient operations. 

The push operation adds elements to both mainStack and maxStack (the latter only if the element is greater than or equal to the current maximum). 

The pop operation removes elements from both stacks only if the popped element is the current maximum. 

The top operation gives the top element of mainStack, and getMax provides the current maximum from maxStack

This design ensures that all stack operations, including retrieving the maximum element, are performed in O(1) time complexity.