-
Notifications
You must be signed in to change notification settings - Fork 13
/
StockPrice.java
49 lines (37 loc) · 1.22 KB
/
StockPrice.java
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
package leetcode.tree.redblacktree;
import java.util.HashMap;
import java.util.TreeMap;
public class StockPrice {
HashMap<Integer, Integer> timestampPrice;
TreeMap<Integer, Integer> priceCount;
int maxTimestamp;
public StockPrice() {
priceCount = new TreeMap<>();
timestampPrice = new HashMap<>();
maxTimestamp = 0;
}
public void update(int timestamp, int price) {
maxTimestamp = Math.max(maxTimestamp, timestamp);
// 管理价格出现的次数
Integer originPrice = timestampPrice.getOrDefault(timestamp, -1);
if (priceCount.containsKey(originPrice)) {
Integer count = priceCount.get(originPrice);
if (count == 1) {
priceCount.remove(originPrice);
} else if (count > 1) {
priceCount.put(originPrice, count - 1);
}
}
priceCount.put(price, priceCount.getOrDefault(price, 0) + 1);
timestampPrice.put(timestamp, price);
}
public int current() {
return timestampPrice.get(maxTimestamp);
}
public int maximum() {
return priceCount.lastKey();
}
public int minimum() {
return priceCount.firstKey();
}
}