1
var StockPrice = function () {
2
// Initialize a Map
3
// Should simply store [timestamp -> value]
4
this.data = new Map();
5

6
// Initialize Max Heap
7
// Should simply store timestamp as value, and price as priority
8
this.max = new MaxPriorityQueue();
9

10
// Initialize Min Heap
11
// Should simply store timestamp as value, and price as priority
12
this.min = new MinPriorityQueue();
13

14
// This is find maximum timestamp i.e. current stock price.
15
this.currentTimestamp = -1;
16
};
17

18
/**
19
* @param {number} timestamp
20
* @param {number} price
21
* @return {void}
22
*/
23
StockPrice.prototype.update = function (timestamp, price) {
24
// Check if its a new timestamp or an update to older
25
this.currentTimestamp = Math.max(this.currentTimestamp, timestamp);
26

27
// Upsert [Insert or Update value] for price at timestamp
28
this.data.set(timestamp, price);
29

30
// insert timestamp to the queue with price is priority
31
this.max.enqueue(timestamp, price);
32
this.min.enqueue(timestamp, price);
33
};
34

35
/**
36
* @return {number}
37
*/
38
StockPrice.prototype.current = function () {
39
// get the data with max timestamp from map
40
return this.data.get(this.currentTimestamp);
41
};
42

43
/**
44
* @return {number}
45
*/
46
StockPrice.prototype.maximum = function () {
47
// check the front of max queue
48
// element -> timestamp
49
// priority -> price
50
let { element, priority } = this.max.front();
51

52
// if priority [i.e. price] is not same latest value, discard it
53
while (priority != this.data.get(element)) {
54
this.max.dequeue();
55

56
element = this.max.front().element;
57
priority = this.max.front().priority;
58
}
59

60
// return price
61
return priority;
62
};
63

64
/**
65
* @return {number}
66
*/
67
StockPrice.prototype.minimum = function () {
68
// check the front of max queue
69
// element -> timestamp
70
// priority -> price
71
let { element, priority } = this.min.front();
72

73
// if priority [i.e. price] is not same latest value, discard it
74
while (priority != this.data.get(element)) {
75
this.min.dequeue();
76

77
element = this.min.front().element;
78
priority = this.min.front().priority;
79
}
80

81
// return price
82
return priority;
83
};
84

85
/**
86
* Your StockPrice object will be instantiated and called as such:
87
* var obj = new StockPrice()
88
* obj.update(timestamp,price)
89
* var param_2 = obj.current()
90
* var param_3 = obj.maximum()
91
* var param_4 = obj.minimum()
92
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0