-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_043.js
41 lines (37 loc) Β· 865 Bytes
/
problem_043.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class MaxStack {
constructor() {
this.stack = [];
this.maxNum = [];
}
/**
* Pushes value into the current stack
* @param {number} val
*/
push(val) {
if(this.maxNum.length === 0
|| val >= this.maxNum[this.maxNum.length - 1]) {
this.maxNum.push(val);
}
this.stack.push(val);
}
/**
* Pops an element, and returns the topmost element of the stack
* @return {number}
*/
pop() {
if (this.stack.length === 0) return null;
const val = this.stack.pop();
// Check to remove from max stack
if (val === this.maxNum[this.maxNum.length - 1]) this.maxNum.pop();
return val;
}
/**
* Returns the maximum value in the stack currently
* @return {number}
*/
max() {
if(this.maxNum.length === 0) return null;
return this.maxNum[this.maxNum.length - 1];
}
}
export default MaxStack;