Skip to content

Instantly share code, notes, and snippets.

@remi-bruguier
Created May 21, 2020 15:06
Show Gist options
  • Save remi-bruguier/d75bf9e5d2efd02a2a5abfe0386159d6 to your computer and use it in GitHub Desktop.
Save remi-bruguier/d75bf9e5d2efd02a2a5abfe0386159d6 to your computer and use it in GitHub Desktop.
Implement a class for a stack that supports all the regular functions (push, pop) and an additional function of max() which returns the maximum element in the stack (return None if the stack is empty). Each method should run in constant time.
class MaxStack {
private stack: number[] = new Array<number>();
private maxStack: number[] = new Array<number>();
private length: number = 0;
public push(item: number): void {
let previousMax = this.maxStack[this.length-1] || 0;
this.maxStack[this.length] = item > previousMax ? item : previousMax;
this.stack[this.length++] = item;
}
public pop(): number {
this.stack.length = this.maxStack.length = --this.length;
return this.stack[this.length];
}
public max(): number | undefined{
return this.maxStack[this.length - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment