Skip to content

Instantly share code, notes, and snippets.

@si-yao
Created September 22, 2015 23:56
Show Gist options
  • Save si-yao/60e4a391733488cd1ba1 to your computer and use it in GitHub Desktop.
Save si-yao/60e4a391733488cd1ba1 to your computer and use it in GitHub Desktop.
class MinStack {
long min;
Stack<Long> stack;
public MinStack() {
min = 0;
stack = new Stack<Long>();
}
public void push(int x) {
if (stack.isEmpty()) {
min = x;
stack.push(0L);
} else {
long dif = x - min;
stack.push(dif);
if (x < min) {
min = x;
}
}
}
public void pop() {
if (stack.peek() >= 0) {
stack.pop();
} else {
min = min - stack.pop();
}
}
public int top() {
if (stack.peek() < 0) {
return (int)min;
} else {
return (int)(min + stack.peek());
}
}
public int getMin() {
return (int)min;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment