forked from jeantimex/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax-stack.js
76 lines (65 loc) · 1.08 KB
/
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Max Stack
*
* The implementation is similar to Min Stack
*/
/**
* initialize your data structure here.
*/
class MaxStack {
constructor() {
this.stack = [];
this.max = null;
}
/**
* @param {number} x
* @return {void}
*/
push(x) {
if (this.stack.length === 0) {
this.stack.push(x);
this.max = x;
return;
}
if (x > this.max) {
// x - this.max > 0
// 2x - this.max > x
// 2x - this.max > new max
this.stack.push(2 * x - this.max);
this.max = x;
} else {
this.stack.push(x);
}
}
/**
* @return {number}
*/
pop() {
const x = this.stack.pop();
if (x > this.max) {
const result = this.max;
this.max = 2 * this.max - x;
return result;
}
if (this.stack.length === 0) {
this.max = null;
}
return x;
}
/**
* @return {number}
*/
top() {
const x = this.stack[this.stack.length - 1];
if (x > this.max) {
return this.max;
}
return x;
}
/**
* @return {number}
*/
getMax() {
return this.max;
}
}