Sobes.tech
Senior

Why can't we just use a single max variable instead of a second stack?

sobes.tech AI

Answer from AI

Using a single variable max instead of a second stack in a problem, such as finding the maximum in a stack, is not suitable because it is necessary to track the maximum for each stack state during push/pop operations.

If only one variable max is stored, then when removing an element from the stack, it will not be possible to correctly restore the previous maximum, as information about previous maximums is lost.

The second stack is used to store the maximums at each level of the stack. When adding an element, compare it with the current maximum and push the larger of the two onto the max stack. When removing an element, simultaneously remove the top element from the max stack, which always allows quick access to the current maximum.

Example:

Stack<Integer> stack = new Stack<>();
Stack<Integer> maxStack = new Stack<>();

void push(int x) {
    stack.push(x);
    if (maxStack.isEmpty() || x >= maxStack.peek()) {
        maxStack.push(x);
    } else {
        maxStack.push(maxStack.peek());
    }
}

void pop() {
    stack.pop();
    maxStack.pop();
}

int getMax() {
    return maxStack.peek();
}

Thus, the second stack ensures correct and efficient tracking of the maximum without losing information when the main stack's contents change.

Why can't we just use a single max variable instead… - sobes.tech