-
-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathmin-max-stack.js
33 lines (29 loc) · 929 Bytes
/
min-max-stack.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
class MinMaxStack {
constructor(){
this.minMaxStack =[];
this.stack = [];
}
peek(){
return this.stack[this.stack.length -1];
}
pop(){
this.minMaxStack.pop();
return this.stack.pop();
}
push(number){
const newMinMax = { min:number, max:number };
if(this.minMaxStack.length){
const lastMinMax = this.minMaxStack[this.minMaxStack.length-1];
newMinMax.min = Math.min(lastMinMax.min, number);
newMinMax.max = Math.max(lastMinMax.max, number);
}
this.minMaxStack.push(newMinMax);
this.stack.push(number);
}
getMin(){
return this.minMaxStack[this.minMaxStack.length-1].min;
}
getMax(){
return this.minMaxStack[this.minMaxStack.length-1].max;
}
};