Implement a stack with a max function

Implement a stack with a max function that returns the maximum value in the stack.

Problem

Implement a stack with a max function that returns the maximum value in the stack.
Example input:
push(1)
push(2)
push(3)
max()
Example output:
3

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The solution below is optimal because it uses a stack to store the values and a variable to store the max value.
// The max value is updated every time a new value is pushed to the stack.
// The max function returns the max value.

class Stack {
  constructor() {
    this.stack = [];
    this.max = null;
  }

  push(value) {
    this.stack.push(value);
    if (this.max === null || value > this.max) {
      this.max = value;
    }
  }

  pop() {
    const value = this.stack.pop();
    if (value === this.max) {
      this.max = Math.max(...this.stack);
    }
    return value;
  }

  max() {
    return this.max;
  }
}

A.I. Evaluation of the Solution

The candidate's solution is correct and uses a stack to store the values and a variable to store the max value. The max value is updated every time a new value is pushed to the stack. The max function returns the max value.

Evaluated at: 2022-11-22 18:15:29