Thursday, July 14, 2016

Finding out running Maximum element from stack

You have an empty sequence, and you will be given  queries. Each query is one of these three types:
  • 1 num  Push the element x into the stack.
  • 2          Delete the element present at the top of the stack.
  • 3          Print the maximum element in the stack.

For each query of type 3 return the max element from the current stack.
Input:
10
1 9
1 7
3 
2
1 20
1 26
2
3
1 45
3
 Output: 
9
20
45 
Approach 1:
Use a temp variable to store a maximum element. When the maximum is removed from the stack, iterate through stack and find out next maximum element.

Approach 2:
When we are removing any element from stack and if its max element, then we will have to re-calculate the maximum from existing stack which would be time consuming task. 
We can use the another stack to store the local maximum for stack so far, by adding element in local maximum stack if its greater than current top element.
Only overhead with the maximum stack is when any of the max is removed from the original stack, we should also remove it from maximum stack.
Code below implement this solution.
import java.util.Scanner;
import java.util.Stack;

public class MaxStack {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int queries = scanner.nextInt();

        Stack integerStack = new Stack();
        Stack localMaxStack = new Stack();

        while (queries > 0) {
            int query = scanner.nextInt();
            queries--;
            switch (query) {
                case 1:
                    int value = scanner.nextInt();
                    integerStack.push(value);
                    if (localMaxStack.isEmpty() || value >= localMaxStack.peek())
                        localMaxStack.push(value);
                    break;
                case 2:
                    if (integerStack.isEmpty()) {
                        System.out.println("Invalid Operation !! Stack Empty");
                        System.exit(-1);
                    }
                    value = integerStack.pop();
                    if (!localMaxStack.isEmpty() && value == localMaxStack.peek())
                        localMaxStack.pop();
                    break;
                case 3:
                    if (!localMaxStack.isEmpty()) {
                        System.out.println(localMaxStack.peek());
                    }else {
                        System.out.println("Stack Empty");
                    }
                    break;
                default:
                    System.out.println("Invalid Operation");
                    System.exit(-1);
            }
        }
    }
}

Comments are welcome.

No comments:

Post a Comment