You are given a series of daily price quotes for a stock, and you need to calculate the stock Span. The stock Span is defined as the number of consecutive days leading up to the current day for which the price of the stock was less than or equal to the price of the current day.
Implement the StockSpanner
class:
StockSpanner()
Initializes the object of the class.int next(int price)
Returns the span of the stock price given that day.We’ll use a stack data structure to maintain prices along with their spans. For each incoming price, we will:
1
.The stack will keep a tuple of (price, span)
. Each next()
operation will have a time complexity of (O(n)) in the worst case, but amortized time complexity is (O(1)) due to each element being pushed and popped from the stack once.
Here’s the implementation of the StockSpanner
class:
class StockSpanner:
def __init__(self):
# Stack to store pairs of (price, span)
self.stack = []
def next(self, price: int) -> int:
span = 1 # Initial span for the current price
# Calculate span by popping all elements less than or equal to the current price
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1]
# Push the current price and its span onto the stack
self.stack.append((price, span))
return span
# Example usage:
# spanner = StockSpanner()
# print(spanner.next(100)) # Output: 1
# print(spanner.next(80)) # Output: 1
# print(spanner.next(60)) # Output: 1
# print(spanner.next(70)) # Output: 2
# print(spanner.next(60)) # Output: 1
# print(spanner.next(75)) # Output: 4
# print(spanner.next(85)) # Output: 6
next()
call.next()
call is (O(1)).next()
calls, as we are storing each price with its span in the stack.This efficient use of stack ensures that we can calculate the span in constant amortized time, making it an optimal solution for this problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?