[Likou] Hash table + ordered set: 2034. Stock price fluctuations

[Likou] Hash table + ordered set: 2034. Stock price fluctuations

1. Introduction to the topic

You are given a data stream of stock prices. Each record in the data stream contains two pieces of data:

  • a timestamp
  • The price corresponding to the stock at this timestamp .

Unfortunately, due to the inherent volatility of the stock market, stock price records may not arrive in chronological order. In some cases, some records may be wrong. If two records with the same timestamp appear in the data stream, the previous record is regarded as an erroneous record, and the record that appears later corrects the previous erroneous record.

1) Please design an algorithm to implement:

  • Update the stock price at a certain timestamp. If there is a previous price at the same timestamp, this operation will correct the previous wrong price.
  • Find the latest stock price in the current record. The latest stock price is defined as the stock price with the latest timestamp.
  • Find the highest price of the stock currently recorded.
  • Find the lowest price of a stock currently recorded.

2) Code to implement StockPrice class:

  • StockPrice() initializes the object. There is currently no stock price record.
  • void update(int timestamp, int price) updates the stock price to price at time point timestamp.
  • int current() returns the latest stock price.
  • int maximum() returns the highest stock price.
  • int minimum() returns the stock's minimum price.

3) Example:
Insert image description here

2. Ideas

1) Since the same timestamp may appear multiple times, subsequent records will correct (overwrite) previous records, so a hash table can be used to record the stock price corresponding to each timestamp.

  • For the operation of returning the latest stock price, we can maintain the maximum timestamp and use the maximum timestamp to search in the hash table to get the latest stock price.
  • For an operation that returns the highest and lowest price of a stock, we need to know the highest and lowest price of the stock currently in the hash table. We can use an ordered set to maintain the stock prices in the hash table. The maximum and minimum values ​​in the ordered set are the highest and lowest prices of the stocks in the current hash table.

Therefore, the StockPrice class needs to contain a maximum timestamp, a hash table, and an ordered collection. When initialized, the maximum timestamp is set to 0, and the hash table and ordered set are set to empty.

  • For update operations:
    • Get the original price corresponding to timestamp timestamp from the hash table. If there is no original price corresponding to timestamp timestamp in the hash table, record the original price as 0 (since the actual prices are greater than 0, you can record the original price as 0 means that the timestamp is not in the hash table);
    • Update the price corresponding to the timestamp timestamp in the hash table to the new price price;
    • If the original price is greater than 0, that is, there is a record corresponding to the timestamp timestamp before, the original price will be deleted from the ordered set;
    • Add new prices to the sorted collection prices.

Note that since there may be duplicate stock prices, for languages ​​that do not support multiple ordered sets (such as multiset in C++), you can additionally record the number of occurrences of each stock price, and update the ordered set when adding or deleting stock prices. The number of occurrences of the stock price. The rest of the operations can get results directly from hash tables and sorted sets:

  • For the operation of returning the latest stock price, obtain the stock price corresponding to the maximum timestamp from the hash table and return it;
  • For the operation of returning the highest stock price, the maximum value is obtained from the ordered set, which is the highest stock price, and is returned;
  • For the operation of returning the lowest price of a stock, the minimum value is obtained from the ordered set, which is the lowest price of the stock, and is returned.

3. Problem solving code

from sortedcontainers import SortedList

class StockPrice:
    def __init__(self):
        self.prices = SortedList()
        self.tpMap = {
    
    }
        self.maxTimestamp = 0

    def update(self, timestamp: int, prices: int) -> None:
        if timestamp in self.tpMap:
            self.prices.discard(self.tpMap[timestamp])	# 删除元素
        self.prices.add(prices)
        self.tpMap[timestamp] = prices
        self.maxTimestamp = max(self.maxTimestamp, timestamp)

    def current(self) -> int:
        return self.tpMap[self.maxTimestamp]

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

    def minimum(self) -> int:
        return self.prices[0]
  • time complexity:

    • The time complexity of initialization is O(1),
    • The time complexity of the update operation, the operation of returning the highest price of the stock and the operation of returning the lowest price of the stock is O(log⁡ n),
    • The time complexity of returning the latest stock price operation is O(1),
    • where n is the number of update operations.
    • The update operation requires updating the maximum timestamp, hash table and ordered set,
      • Updating the maximum timestamp and hash table takes O(1) time,
      • Updating a sorted set takes O(log⁡ n) time.
      • The operation of returning the highest stock price and the operation of returning the lowest stock price respectively require searching for the maximum value and minimum value in the ordered set, which requires O(log⁡ n) time.
    • The operation of returning the latest stock price requires obtaining the stock price corresponding to the maximum timestamp in the hash table, which takes O(1) time.
  • Space complexity: O(n), where n is the number of update operations. The space complexity mainly depends on the hash table and ordered set. The number of elements stored in the hash table and ordered set will not exceed the number of update operations.

4. Danger

LeetCode is a brand under LeetCode Network that focuses on the technical growth of programmers and enterprise technical talent services. Originating from Silicon Valley in the United States, Likou provides a professional IT technology professional improvement platform for programmers around the world, effectively helping programmers achieve rapid progress and long-term growth. In addition, LeetCode is committed to solving the pain points of programmers' technical assessment, training, and career matching, and gradually leading the professionalization of Internet technology job hunting and recruitment.

  • According to what we have learned, Easy questions and Medium questions are relatively common in interviews. They usually appear in the form of handwritten code. You need to analyze the questions and give answers, and communicate with the interviewer. Sometimes You are asked to analyze the time complexity 8 and space complexity °. The interviewer will use your analysis and answers to the questions to understand your familiarity with commonly used algorithms and your program implementation skills.
  • In some positions that require a high level of algorithm and program implementation skills, Hard questions are also very popular with interviewers. If you successfully bug-free a Hard question during the interview, we believe you will leave a lot of impressions on the interviewer. It will leave a deep impression and greatly increase the probability of getting an offer. According to relevant statistics, if you successfully solve a Hard question in the interview, the probability of not getting an offer is infinitely close to 0.
  • Therefore, Easy and Medium in Likou are equivalent to the regular questions in the interview, while Hard is equivalent to the more difficult questions in the interview. If you solve the Hard question, the Offer can be said to be in your pocket.

reference

【1】https://leetcode.cn/problems/stock-prices-fluctuation

Guess you like

Origin blog.csdn.net/qq_51392112/article/details/133678686