Skip to content

Instantly share code, notes, and snippets.

@bard86
Last active July 29, 2024 12:51
Show Gist options
  • Save bard86/38c88f5304bfca32b65a13ed9676c144 to your computer and use it in GitHub Desktop.
Save bard86/38c88f5304bfca32b65a13ed9676c144 to your computer and use it in GitHub Desktop.
package ru.sber;
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
MyStack s = new MyStack();
s.push(1);
s.push(-2);
s.push(7);
s.push(3);
s.push(Integer.MAX_VALUE);
s.push(Integer.MIN_VALUE);
s.push(9);
s.push(-1);
for (int counter=0; counter<8; counter++) {
System.out.println("max=" + s.max() + "; value=" + s.pop());
}
}
static class MyStack {
private final Deque<Node> stack = new ArrayDeque<>();
public void push(Integer value) {
int maxValue = Math.max(value, max());
stack.push(new Node(value, maxValue));
}
public Integer pop() {
return stack.pop().value;
}
public Integer max() {
if (stack.isEmpty()) {
return Integer.MIN_VALUE;
}
return stack.peek().max;
}
}
static class Node {
private final int value;
private final int max;
public Node(int value, int max) {
this.value = value;
this.max = max;
}
public int getValue() {
return value;
}
public int getMax() {
return max;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment