Share my Java solution with ONLY ONE stack
The question is ask to construct One stack. So I am using one stack.\n\nThe idea is to store the gap between the min value and the current value; \n\nThe proble
The question is ask to construct One stack. So I am using one stack.\n\nThe idea is to store the gap between the min value and the current value; \n\nThe problem for my solution is the cast. I have no idea to avoid the cast. Since the possible gap between the current value and the min value could be Integer.MAX_VALUE-Integer.MIN_VALUE;\n\n\n\n\n\n    public class MinStack {\n        long min;\n        Stack<Long> stack;\n    \n        public MinStack(){\n            stack=new Stack<>();\n        }\n        \n        public void push(int x) {\n            if (stack.isEmpty()){\n                stack.push(0L);\n                min=x;\n            }else{\n                stack.push(x-min);//Could be negative if min value needs to change\n                if (x<min) min=x;\n            }\n        }\n    \n        public void pop() {\n            if (stack.isEmpty()) return;\n            \n            long pop=stack.pop();\n            \n            if (pop<0)  min=min-pop;//If negative, increase the min value\n            \n        }\n    \n        public int top() {\n            long top=stack.peek();\n            if (top>0){\n                return (int)(top+min);\n            }else{\n               return (int)(min);\n            }\n        }\n    \n        public int getMin() {\n            return (int)min;\n        }\n    }
['Java']