Day 26
Date: October 21, 2022 9:30 AM
LinkedIn: https://leetcode.cn/problems/online-stock-span/
Title: 股票价格跨度
单调栈
在Python类中规定,函数的第一个参数是实例对象本身,并且约定俗成,把其名字写为**self。**其作用相当于java中的this,表示当前类的对象,可以调用当前类中的属性和方法。
class StockSpanner:
def __init__(self):
self.stack = [] # stack [price, cnt] # price是价格 cnt为对应跨度
def next(self, price: int) -> int:
cnt = 1 #跨度
while self.stack and self.stack[-1][0] <= price: #栈不空或者栈顶的价格小于等于当前价格
cnt += self.stack.pop()[1] # 跨度加上当前遍历到的价格的跨度
self.stack.append([price, cnt]) # 新的入栈
return cnt
# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)