Find maximum in stack in O(1) without using additional stack in C++


Suppose we want to make a stack that can store the maximum element in the stack. And we can get it in O(1) time. The constraint is that, it should not use any additional space, so O(1) extra space.

We can make one user-defined stack, that will store the max value, when one operation is performed, like pop or peek, then the max will be returned. For peek operation, return the maximum of stack top and the max element, for pop operation, when the top element is larger, then print it and update max as 2*max – top_element. otherwise return top_element. For push operation update the max element as x(data to be inserted), 2*x – max.

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
class CustomStack {
   stack<int> stk;
   int stack_max;
   public:
   void getMax() {
      if (stk.empty())
         cout << "Stack is empty"<<endl;
      else
         cout << "Maximum Element in the stack is: "<< stack_max <<endl;
   }
   void peek() {
      if (stk.empty()) {
         cout << "Stack is empty ";
         return;
      }
      int top = stk.top(); // Top element.
      cout << "Top Most Element is: "<<endl;
      (top > stack_max) ? cout << stack_max : cout << top;
   }
   void pop() {
      if (stk.empty()) {
         cout << "Stack is empty"<<endl;
         return;
      }
      cout << "Top Most Element Removed: ";
      int top = stk.top();
      stk.pop();
      if (top > stack_max) {
         cout << stack_max <<endl;
         stack_max = 2 * stack_max - top;
      } else
         cout << top <<endl;
   }
   void push(int element) {
      if (stk.empty()) {
         stack_max = element;
         stk.push(element);
         cout << "Element Inserted: " << element <<endl;
         return;
      }
      if (element > stack_max) {
         stk.push(2 * element - stack_max);
         stack_max = element;
      } else
      stk.push(element);
      cout << "Element Inserted: " << element <<endl;
   }
};
int main() {
   CustomStack stk;
   stk.push(4);
   stk.push(6);
   stk.getMax();
   stk.push(8);
   stk.push(20);
   stk.getMax();
   stk.pop();
   stk.getMax();
   stk.pop();
   stk.peek();
}

Output

Element Inserted: 4
Element Inserted: 6
Maximum Element in the stack is: 6
Element Inserted: 8
Element Inserted: 20
Maximum Element in the stack is: 20
Top Most Element Removed: 20
Maximum Element in the stack is: 8
Top Most Element Removed: 8
Top Most Element is:
6

Updated on: 17-Dec-2019

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements