Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:19
Show Gist options
  • Save HDegano/bb6670abb9a021a5b4ab to your computer and use it in GitHub Desktop.
Save HDegano/bb6670abb9a021a5b4ab to your computer and use it in GitHub Desktop.
Stack with Min/Max operation constant time.
public class MinStack {
private Stack<int> _stack = new Stack<int>();
private Stack<int> _min = new Stack<int>();
public void Push(int x) {
_stack.Push(x);
if(_min.Count == 0) _min.Push(x);
else {
if(x <= _min.Peek())
_min.Push(x);
}
}
public void Pop() {
if(_stack.Pop() == _min.Peek())
_min.Pop();
}
public int Top() {
return _stack.Peek();
}
public int GetMin() {
return _min.Peek();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment