/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
publicclassMinStack { long min; Stack<Long> stack;
publicMinStack(){ stack=newStack<>(); } publicvoidpush(int x) { if (stack.isEmpty()){ stack.push(0L); min=x; }else{ stack.push(x-min);//Could be negative if min value needs to change if (x<min) min=x; } }
publicvoidpop() { if (stack.isEmpty()) return; long pop=stack.pop(); if (pop<0) min=min-pop;//If negative, increase the min value }
publicinttop() { long top=stack.peek(); if (top>0){ return (int)(top+min); }else{ return (int)(min); } }