2034. 股票价格波动

exiaohu 于 2022-01-23 发布

题目链接:2034. 股票价格波动

原来 leetcode 上可以直接使用 sortedcontainers 这样的非标准库,那就省事儿多了。

sortedcontainers.SortedList 里,添加、删除和索引一个元素的时间复杂度都是 $O(log(n))$,相当于一个二叉排序树。

from sortedcontainers import SortedList


class StockPrice:
    def __init__(self):
        self.prices = dict()
        self.latest_timestamp = 0
        self.sorted_prices = SortedList()

    def update(self, timestamp: int, price: int) -> None:
        if timestamp in self.prices and self.prices.get(timestamp) != price:
            self.sorted_prices.discard(self.prices.get(timestamp))
        elif timestamp in self.prices and self.prices.get(timestamp) == price:
            return

        self.latest_timestamp = max(timestamp, self.latest_timestamp)
        self.prices[timestamp] = price
        self.sorted_prices.add(price)

    def current(self) -> int:
        return self.prices.get(self.latest_timestamp, 0)

    def maximum(self) -> int:
        return self.sorted_prices[-1]

    def minimum(self) -> int:
        return self.sorted_prices[0]


# Your StockPrice object will be instantiated and called as such:
# obj = StockPrice()
# obj.update(timestamp,price)
# param_2 = obj.current()
# param_3 = obj.maximum()
# param_4 = obj.minimum()