AlgoMaster Logo

Stock Price Fluctuation

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with List

Intuition:

The brute force approach is fairly straightforward. We maintain a list of pairs and simply update or query the list as required. This approach will straightforwardly tackle the problem but will have inefficiencies especially given the constraints.

Code:

Complexity Analysis:

2. Using HashMap for Tracking Prices

Intuition:

Using a HashMap allows for more efficient updates. By keeping track of the prices with their timestamps in a map, the update and current operations become more efficient. However, we still need list-like structures to calculate max and min in a straightforward method or employ further structures to maintain these values efficiently.

Code:

3. Using TreeMap for Efficient Ordering

Intuition:

TreeMap inherently sorts its keys, providing a way to efficiently find min and max along with an easy way to get the current price using the highest timestamp. This allows all operations to be more efficient except adding or removing, which are logarithmic due to the properties of the TreeMap.

Code: