Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
[7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days.[7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days.Implement the StockSpanner class:
StockSpanner() Initializes the object of the class.int next(int price) Returns the span of the stock's price given that today's price is price.Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation
104 calls will be made to next.The brute force approach involves keeping track of all the stock prices encountered so far and then, for each new price, iterating backwards through the stored prices to calculate the span directly. This means, for each price, we need to traverse backwards until a price higher than the current price is found.
n calls to the next method because we might need to traverse all previous prices for each call.To optimize the previous approach, we can utilize a stack to maintain a history of price indices that help in quickly determining the span. We store prices along with their respective spans in a stack. Each time a price is added, all prices less than or equal to the current price are popped from the stack, effectively calculating the span in constant amortized time.
next, because each element is pushed and popped from the stack at most once.n is the number of prices recorded.