901. Online Stock Span
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day
Example 1:
- Input: ``
- Output: ``
- Explanation: 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 StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return1stockSpanner.next(80); // return1stockSpanner.next(60); // return1stockSpanner.next(70); // return2stockSpanner.next(60); // return1stockSpanner.next(75); // return4, because the last4prices (including today’spriceof75) were less than or equal to today’sprice. stockSpanner.next(85); // return6
Constraints:
1 <= price <= 10^5- At most 10^4 calls will be made to next.
Solution
class StockSpanner:
def __init__(self):
self.stack = []
def next(self, price: int) -> int:
ans = 1
while self.stack and self.stack[-1][0] <= price:
ans += self.stack.pop()[1]
self.stack.append([price, ans])
return ans
# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)