class maxStack { constructor() { this.s = []; this.maxS = []; } push(int) { this.s.push(int); if (Math.max(this.maxS) === null || int >= Math.max.apply(null, this.maxS)) { this.maxS.push(int); } console.log(this.maxS); } // Remove and return the top item from our stack. If it equals // the top item in maxesStack, they must have been pushed in together. // So we'll pop it out of maxesStack too. pop() { const item = this.s.pop(); if (item === Math.max.apply(null, this.maxS)) { this.maxS.pop(); } return item; } // The last item in maxesStack is the max item in our stack. getMax() { console.log(Math.max.apply(null, this.maxS)); return Math.max.apply(null, this.maxS); } } const test = new maxStack(); test.push(2); test.push(4); test.push(6); test.pop(6); console.log(test.getMax());