-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path2034-stock-price-fluctuation.cpp
99 lines (84 loc) · 2.55 KB
/
2034-stock-price-fluctuation.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Gets TLE
/*
class StockPrice {
unordered_map<int, int> stockToPrice;
int curr = INT_MIN;
public:
StockPrice() { }
void update(int timestamp, int price) {
stockToPrice[timestamp] = price;
curr = max(curr, timestamp);
}
int current() {
return stockToPrice[curr];
}
int maximum() {
int maxPrice = INT_MIN;
for (auto [key,val]: stockToPrice) maxPrice = max(maxPrice, val);
return maxPrice;
}
int minimum() {
int minPrice = INT_MAX;
for (auto [key,val]: stockToPrice) minPrice = min(minPrice, val);
return minPrice;
}
};
class StockPrice {
int latestTime;
// Store price of each stock at each timestamp.
unordered_map<int, int> timestampPriceMap;
// Store stock prices in sorted order to get min and max price.
priority_queue<pair<int, int>> maxHeap;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;
public:
StockPrice() {
latestTime = 0;
}
void update(int timestamp, int price) {
// Update latestTime to latest timestamp.
latestTime = max(latestTime, timestamp);
// Add latest price for timestamp.
timestampPriceMap[timestamp] = price;
minHeap.push({ price, timestamp });
maxHeap.push({ price, timestamp });
}
int current() {
// Return latest price of the stock.
return timestampPriceMap[latestTime];
}
int maximum() {
pair<int, int> top = maxHeap.top();
// Pop pairs from heap with the price doesn't match with hashmap.
while (timestampPriceMap[top.second] != top.first) {
maxHeap.pop();
top = maxHeap.top();
}
return top.first;
}
int minimum() {
pair<int, int> top = minHeap.top();
// Pop pairs from heap with the price doesn't match with hashmap.
while (timestampPriceMap[top.second] != top.first) {
minHeap.pop();
top = minHeap.top();
}
return top.first;
}
};
*/
class StockPrice {
map<int, int> m;
multiset<int> prices;
public:
void update(int timestamp, int price) {
if (m.count(timestamp)) {
auto prevPrice = m[timestamp];
prices.erase(prices.find(prevPrice));
}
prices.insert(price);
m[timestamp] = price;
}
int current() { return rbegin(m)->second; }
int maximum() { return *rbegin(prices); }
int minimum() { return *begin(prices); }
};