philosyang.com

901. Online Stock Span | 1709

It’s a monotonic stack problem!

 1class StockSpanner:
 2
 3    def __init__(self):
 4        self.history = deque([])
 5
 6    def next(self, price: int) -> int:
 7        result = 1
 8        while self.history and self.history[-1][0] <= price:
 9            result += self.history.pop()[1]
10
11        self.history.append((price, result))
12        return result
13
14
15# Your StockSpanner object will be instantiated and called as such:
16# obj = StockSpanner()
17# param_1 = obj.next(price)

#Stack #Python