返回介绍

solution / 2000-2099 / 2034.Stock Price Fluctuation / README_EN

发布于 2024-06-17 01:03:11 字数 8960 浏览 0 评论 0 收藏 0

2034. Stock Price Fluctuation

中文文档

Description

You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.

Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.

Design an algorithm that:

  • Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.
  • Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.
  • Finds the maximum price the stock has been based on the current records.
  • Finds the minimum price the stock has been based on the current records.

Implement the StockPrice class:

  • StockPrice() Initializes the object with no price records.
  • void update(int timestamp, int price) Updates the price of the stock at the given timestamp.
  • int current() Returns the latest price of the stock.
  • int maximum() Returns the maximum price of the stock.
  • int minimum() Returns the minimum price of the stock.

 

Example 1:

Input
["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]
[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
Output
[null, null, null, 5, 10, null, 5, null, 2]

Explanation
StockPrice stockPrice = new StockPrice();
stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].
stockPrice.update(2, 5);  // Timestamps are [1,2] with corresponding prices [10,5].
stockPrice.current();   // return 5, the latest timestamp is 2 with the price being 5.
stockPrice.maximum();   // return 10, the maximum price is 10 at timestamp 1.
stockPrice.update(1, 3);  // The previous timestamp 1 had the wrong price, so it is updated to 3.
              // Timestamps are [1,2] with corresponding prices [3,5].
stockPrice.maximum();   // return 5, the maximum price is 5 after the correction.
stockPrice.update(4, 2);  // Timestamps are [1,2,4] with corresponding prices [3,5,2].
stockPrice.minimum();   // return 2, the minimum price is 2 at timestamp 4.

 

Constraints:

  • 1 <= timestamp, price <= 109
  • At most 105 calls will be made in total to update, current, maximum, and minimum.
  • current, maximum, and minimum will be called only after update has been called at least once.

Solutions

Solution 1: Hash Table + Ordered Set

We define the following data structures or variables:

  • d: a hash table that stores the timestamp and the corresponding price;
  • ls: an ordered set that stores all prices;
  • last: the timestamp of the last update.

Then, we can perform the following operations:

  • update(timestamp, price): update the price corresponding to the timestamp timestamp to price. If timestamp already exists, we need to first remove its corresponding price from the ordered set, and then update it to price. Otherwise, we directly update it to price. Then, we need to update last to max(last, timestamp). The time complexity is O(log n).
  • current(): return the price corresponding to last. The time complexity is $O(1)$.
  • maximum(): return the maximum value in the ordered set. The time complexity is $O(\log n)$.
  • minimum(): return the minimum value in the ordered set. The time complexity is $O(\log n)$.

The space complexity is $O(n)$, where $n$ is the number of update operations.

from sortedcontainers import SortedList


class StockPrice:
  def __init__(self):
    self.d = {}
    self.ls = SortedList()
    self.last = 0

  def update(self, timestamp: int, price: int) -> None:
    if timestamp in self.d:
      self.ls.remove(self.d[timestamp])
    self.d[timestamp] = price
    self.ls.add(price)
    self.last = max(self.last, timestamp)

  def current(self) -> int:
    return self.d[self.last]

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

  def minimum(self) -> int:
    return self.ls[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()
class StockPrice {
  private Map<Integer, Integer> d = new HashMap<>();
  private TreeMap<Integer, Integer> ls = new TreeMap<>();
  private int last;

  public StockPrice() {
  }

  public void update(int timestamp, int price) {
    if (d.containsKey(timestamp)) {
      int old = d.get(timestamp);
      if (ls.merge(old, -1, Integer::sum) == 0) {
        ls.remove(old);
      }
    }
    d.put(timestamp, price);
    ls.merge(price, 1, Integer::sum);
    last = Math.max(last, timestamp);
  }

  public int current() {
    return d.get(last);
  }

  public int maximum() {
    return ls.lastKey();
  }

  public int minimum() {
    return ls.firstKey();
  }
}

/**
 * Your StockPrice object will be instantiated and called as such:
 * StockPrice obj = new StockPrice();
 * obj.update(timestamp,price);
 * int param_2 = obj.current();
 * int param_3 = obj.maximum();
 * int param_4 = obj.minimum();
 */
class StockPrice {
public:
  StockPrice() {
  }

  void update(int timestamp, int price) {
    if (d.count(timestamp)) {
      ls.erase(ls.find(d[timestamp]));
    }
    d[timestamp] = price;
    ls.insert(price);
    last = max(last, timestamp);
  }

  int current() {
    return d[last];
  }

  int maximum() {
    return *ls.rbegin();
  }

  int minimum() {
    return *ls.begin();
  }

private:
  unordered_map<int, int> d;
  multiset<int> ls;
  int last = 0;
};

/**
 * Your StockPrice object will be instantiated and called as such:
 * StockPrice* obj = new StockPrice();
 * obj->update(timestamp,price);
 * int param_2 = obj->current();
 * int param_3 = obj->maximum();
 * int param_4 = obj->minimum();
 */
type StockPrice struct {
  d  map[int]int
  ls   *redblacktree.Tree
  last int
}

func Constructor() StockPrice {
  return StockPrice{
    d:  make(map[int]int),
    ls:   redblacktree.NewWithIntComparator(),
    last: 0,
  }
}

func (this *StockPrice) Update(timestamp int, price int) {
  merge := func(rbt *redblacktree.Tree, key, value int) {
    if v, ok := rbt.Get(key); ok {
      nxt := v.(int) + value
      if nxt == 0 {
        rbt.Remove(key)
      } else {
        rbt.Put(key, nxt)
      }
    } else {
      rbt.Put(key, value)
    }
  }
  if v, ok := this.d[timestamp]; ok {
    merge(this.ls, v, -1)
  }
  this.d[timestamp] = price
  merge(this.ls, price, 1)
  this.last = max(this.last, timestamp)
}

func (this *StockPrice) Current() int {
  return this.d[this.last]
}

func (this *StockPrice) Maximum() int {
  return this.ls.Right().Key.(int)
}

func (this *StockPrice) Minimum() int {
  return this.ls.Left().Key.(int)
}

/**
 * Your StockPrice object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Update(timestamp,price);
 * param_2 := obj.Current();
 * param_3 := obj.Maximum();
 * param_4 := obj.Minimum();
 */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文