-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock_price.cpp
More file actions
62 lines (55 loc) · 1.4 KB
/
stock_price.cpp
File metadata and controls
62 lines (55 loc) · 1.4 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
/*
* =====================================================================================
*
* Filename: stock_price.cpp
*
* Description: 2034. Stock Price Fluctuation
*
* Version: 1.0
* Created: 11/17/2025 10:15:55
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <map>
#include <set>
#include <utility>
class StockPrice {
public:
StockPrice() {}
void update(int timestamp, int price) {
auto it = price_records_.find(timestamp);
if (it != price_records_.end()) {
ordered_prices_.erase({it->second, timestamp});
it->second = price;
} else {
price_records_[timestamp] = price;
}
ordered_prices_.insert({price, timestamp});
}
int current() {
if (price_records_.empty()) {
return 0;
}
return price_records_.rbegin()->second;
}
int maximum() {
if (ordered_prices_.empty()) {
return 0;
}
return ordered_prices_.rbegin()->first;
}
int minimum() {
if (ordered_prices_.empty()) {
return 0;
}
return ordered_prices_.begin()->first;
}
private:
std::map<int, int> price_records_; // timestamp -> price, sorted by timestamp
std::set<std::pair<int, int>> ordered_prices_; // sorted by {price, timestamp}
};