Skip to content

Commit 80a8b9e

Browse files
authored
Create 2034-stock-price-fluctuation.js
1 parent 0c50b87 commit 80a8b9e

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

2034-stock-price-fluctuation.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
const StockPrice = function () {
2+
this.timeToPrice = new Map()
3+
this.lastTime = 0
4+
this.minPrices = new MinPriorityQueue({ priority: (stock) => stock.price })
5+
this.maxPrices = new MaxPriorityQueue({ priority: (stock) => stock.price })
6+
}
7+
8+
/**
9+
* @param {number} timestamp
10+
* @param {number} price
11+
* @return {void}
12+
*/
13+
StockPrice.prototype.update = function (timestamp, price) {
14+
this.timeToPrice.set(timestamp, price)
15+
this.lastTime = Math.max(this.lastTime, timestamp)
16+
this.minPrices.enqueue({ timestamp, price })
17+
this.maxPrices.enqueue({ timestamp, price })
18+
}
19+
20+
/**
21+
* @return {number}
22+
*/
23+
StockPrice.prototype.current = function () {
24+
return this.timeToPrice.get(this.lastTime)
25+
}
26+
27+
/**
28+
* @return {number}
29+
*/
30+
StockPrice.prototype.maximum = function () {
31+
while (
32+
this.maxPrices.front().element.price !==
33+
this.timeToPrice.get(this.maxPrices.front().element.timestamp)
34+
) {
35+
this.maxPrices.dequeue()
36+
}
37+
38+
return this.maxPrices.front().element.price
39+
}
40+
41+
/**
42+
* @return {number}
43+
*/
44+
StockPrice.prototype.minimum = function () {
45+
while (
46+
this.minPrices.front().element.price !==
47+
this.timeToPrice.get(this.minPrices.front().element.timestamp)
48+
) {
49+
this.minPrices.dequeue()
50+
}
51+
52+
return this.minPrices.front().element.price
53+
}
54+
55+
/**
56+
* Your StockPrice object will be instantiated and called as such:
57+
* var obj = new StockPrice()
58+
* obj.update(timestamp,price)
59+
* var param_2 = obj.current()
60+
* var param_3 = obj.maximum()
61+
* var param_4 = obj.minimum()
62+
*/

0 commit comments

Comments
 (0)