--- tags: leetcode --- # [2034. Stock Price Fluctuation](https://leetcode.com/problems/stock-price-fluctuation/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= class StockPrice { public: StockPrice() { currTime = 1; } void update(int timestamp, int price) { auto iter = records.find(timestamp); if (iter == records.end()) { records[timestamp] = price; allPrices.insert(price); if (currTime < timestamp) { currTime = timestamp; } return; } // timestamp exists, so update the old price. // iter->second is the old price. allPrices.erase(allPrices.find(iter->second)); allPrices.insert(price); iter->second = price; } int current() { return records[currTime]; } int maximum() { return *allPrices.rbegin(); } int minimum() { return *allPrices.begin(); } private: multiset<int> allPrices; unordered_map<int, int> records; int currTime; }; /** * 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(); */ ``` ## Time Complexity ## Space Complexity # Miscellane <!-- # Test Cases ``` ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"] [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []] ``` * Wrong Answer: ``` ["StockPrice","update","minimum","update","update","minimum","minimum","update","maximum","update","minimum","current","minimum","update","current","minimum","current","current","update","maximum","maximum","update","minimum","minimum","maximum","maximum","update","maximum","current","maximum","minimum","minimum","update","current"] [[],[45,9233],[],[55,9651],[37,3902],[],[],[25,4833],[],[53,4521],[],[],[],[22,1161],[],[],[],[],[55,6897],[],[],[20,5354],[],[],[],[],[30,5623],[],[],[],[],[],[25,2725],[]] ``` * Time Limit Exceeded: https://leetcode.com/submissions/detail/718584428/testcase/ -->