Senior
Write your own class that implements a stack with methods push, pop, and peekMax, which returns the max element in the stack in O(1).
sobes.tech AI
Answer from AI
Below is an example of a stack class in Java with methods push, pop, and peekMax, where peekMax returns the maximum element in O(1) time thanks to an additional stack for storing maximums:
import java.util.Stack;
public class MaxStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> maxStack = new Stack<>();
public void push(int x) {
stack.push(x);
if (maxStack.isEmpty() || x >= maxStack.peek()) {
maxStack.push(x);
}
}
public int pop() {
int val = stack.pop();
if (val == maxStack.peek()) {
maxStack.pop();
}
return val;
}
public int peekMax() {
return maxStack.peek();
}
}
In this solution, maxStack stores the current maximums. When adding an element, if it is greater than or equal to the current maximum, it is pushed onto maxStack. When removing an element, if it equals the maximum, the maximum is also removed. This allows retrieving the maximum in constant time.