-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0716-max-stack.js
More file actions
69 lines (62 loc) · 1.74 KB
/
0716-max-stack.js
File metadata and controls
69 lines (62 loc) · 1.74 KB
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
/**
* Max Stack
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var MaxStack = function () {
this.mainStack = [];
this.maximumHeap = new PriorityQueue((elementA, elementB) => {
if (elementA.value === elementB.value) {
return elementB.identifier - elementA.identifier;
}
return elementB.value - elementA.value;
});
this.currentIdentifier = 0;
this.removedElements = new Set();
};
MaxStack.prototype.push = function (x) {
const uniqueId = this.currentIdentifier++;
const dataNode = { value: x, identifier: uniqueId };
this.mainStack.push(dataNode);
this.maximumHeap.enqueue(dataNode);
};
MaxStack.prototype.pop = function () {
this.pruneStack();
const poppedElement = this.mainStack.pop();
this.removedElements.add(poppedElement.identifier);
return poppedElement.value;
};
MaxStack.prototype.top = function () {
this.pruneStack();
const topStackNode = this.mainStack[this.mainStack.length - 1];
return topStackNode.value;
};
MaxStack.prototype.peekMax = function () {
this.pruneMaxHeap();
const topHeapElement = this.maximumHeap.front();
return topHeapElement.value;
};
MaxStack.prototype.popMax = function () {
this.pruneMaxHeap();
const maxExtractedNode = this.maximumHeap.dequeue();
this.removedElements.add(maxExtractedNode.identifier);
return maxExtractedNode.value;
};
MaxStack.prototype.pruneStack = function () {
while (
this.mainStack.length > 0 &&
this.removedElements.has(
this.mainStack[this.mainStack.length - 1].identifier,
)
) {
this.mainStack.pop();
}
};
MaxStack.prototype.pruneMaxHeap = function () {
while (
this.maximumHeap.size() > 0 &&
this.removedElements.has(this.maximumHeap.front().identifier)
) {
this.maximumHeap.dequeue();
}
};