Sobes.tech
Junior — Senior

Stack that can return the current maximum in O(1)

livecode

Task condition

It is necessary to implement a data structure "stack" that supports the following operations:

  • push(x) — add an element to the stack;
  • pop() — remove the top element of the stack;
  • top() — get the value of the top element without removing it;
  • getMax() — return the maximum value among all elements in the stack in constant time.
public class MaxStack {
    public void push(int x) {
        // ...
    }

    public void pop() {
        // ...
    }

    public int top() {
        // ...
    }

    public int getMax() {
        // ...
    }
}