This solution looks incorrect and doesn't cover the case when the max value is popped.
For example,
const stack = new Stack();
stack.data = [];
stack.insert(1);
stack.pop();
console.log(stack.maxVal); // even though stack is empty, this will print 1, right?
I think one naive way to solve this is to store (internally) the max value along with the element value, at time of element insertion.
class Entry {
constructor(value, maxValue) {
this.value = value;
this.maxValue = maxValue;
}
}
// insert 1
[new Entry(1, 1)]
// insert 2
[new Entry(1, 1), new Entry(2, 2)]
// insert 1 - notice how the latest Entry has a value property of 1 but a maxValue property of 2 since the largest property seen so far is 2
[new Entry(1, 1), new Entry(2, 2), new Entry(1, 2)]
// pop - look at last Entry's max value to see max value (2)
[new Entry(1, 1), new Entry(2, 2)]
// pop - look at last Entry's max value to see max value (1)
[new Entry(1, 1)]
// pop - empty, so max value is undefined / null
[]
One way to implement this would be something like this
class Stack {
constructor() {
this.entries = [];
}
get maxValue() {
// this value can be stored in an instance variable and updated on pop/push if access to value will occur frequently
if (0 < this.entries.length) {
return this.entries[this.entries.length - 1].maxValue;
}
return null;
}
pop() {
return this.entries.pop();
}
push(value) {
this.entries.push(
new Entry(
value,
Math.max(
value,
this.maxValue
)
)
);
}
}
Another thing to watch out for - in every call to insert you are instantiating a new CheckMax instance which seems wasteful. CheckMax doesn't really contain any state and the this is referring to an instance of a Stack. I think it's more natural to add the logic in CheckMax on Stack itself.
Finally, the setting of the data property on a Stack instance seems like an internal implementation detail that the caller should not be worried about. I don't think the caller should have to initialize the data property on a Stack instance in order for it to work correctly. Whatever data structure the stack uses under the hood to keep track of elements should not be the concern of the caller of the stack.
push[2, 1, 5]the max is 5. However if youpopthe 5 the max remains 5 (should be 2)., If you then push a 4 the max is still 5 (should be 4). You need to recalculate the max each time the stack size changes, not just on thepushwhat you calledinsert(BTW Stacks don't insert) \$\endgroup\$