LeetCode 2034: Stock Price Fluctuation Solution
Master LeetCode problem 2034 (Stock Price Fluctuation ), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2034. Stock Price Fluctuation
Problem Explanation
Explanation
To solve this problem, we can use a combination of data structures to efficiently store and retrieve the stock prices. We can maintain a TreeMap or a SortedMap to store the prices sorted by timestamp. Additionally, we can maintain a separate max-heap and min-heap to keep track of the maximum and minimum prices respectively.
- Initialization: Initialize TreeMap to store timestamp-price pairs and initialize max-heap and min-heap.
- Update Function: Update the TreeMap with the new price at the given timestamp. Update the max-heap and min-heap accordingly.
- Current Function: Retrieve the latest price from the TreeMap.
- Maximum Function: Retrieve the maximum price from the max-heap.
- Minimum Function: Retrieve the minimum price from the min-heap.
The time complexity for each function is O(log n) due to TreeMap operations and heap operations. The space complexity is O(n) to store the timestamp-price pairs in the TreeMap and the max-heap and min-heap.
Solution Code
import java.util.*;
class StockPrice {
TreeMap<Integer, Integer> prices;
PriorityQueue<Integer> maxHeap;
PriorityQueue<Integer> minHeap;
public StockPrice() {
prices = new TreeMap<>();
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap = new PriorityQueue<>();
}
public void update(int timestamp, int price) {
if (prices.containsKey(timestamp)) {
int oldPrice = prices.get(timestamp);
maxHeap.remove(oldPrice);
minHeap.remove(oldPrice);
}
prices.put(timestamp, price);
maxHeap.offer(price);
minHeap.offer(price);
}
public int current() {
return prices.get(prices.lastKey());
}
public int maximum() {
return maxHeap.peek();
}
public int minimum() {
return minHeap.peek();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2034 (Stock Price Fluctuation )?
This page provides optimized solutions for LeetCode problem 2034 (Stock Price Fluctuation ) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2034 (Stock Price Fluctuation )?
The time complexity for LeetCode 2034 (Stock Price Fluctuation ) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2034 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2034 in Java, C++, or Python.