Monday, April 24, 2017

Track the Maximum Element in a Stack

Aim: To find out the maximum element in stack. There can be n-number of push and pop operations. At a given point of time, goal is to get maximum element from stack in O(1).

Solution:

1. Create two stacks, one for storing elements and the other auxiliary stack for tracking the maximum element.

2. Initially, enter the first element in both the stacks. After that, insert new element in first stack. Compare top element from auxiliary stack with current element and insert whichever is greater.

3. Whenever any element is popped from first stack, pop element from other stack as well.

4. At any point of time if you want to get maximum element, then simply print the top element from the auxiliary stack.

Code:




 The time complexity get the maximum element is O(1).


No comments:

Post a Comment

Simple Binary Tree Program

Simple Binary Tree: In this blog we will see, how to create a simple binary tree. We will be using Queue  data structure to store the las...