每个 price 的上一个更大元素距离当前有多远。
更大【被切断】 小 小 当前
class StockSpanner:
# 栈的元素 为 股票下标 和 股票价格 的二元对 单调递减栈
def __init__(self):
self.stack = [(-1, inf)] # 下标 价格 单调递减 始终在栈底 无需处理栈为空
self.idx = -1
def next(self, price: int) -> int:
self.idx += 1 # 记录当前下标
while price >= self.stack[-1][1]:
self.stack.pop() # 更小的后续不会用到了
self.stack.append((self.idx, price))
return self.idx - self.stack[-2][0] # -1 为 inf
# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)
class StockSpanner {
public:
StockSpanner() {
this->stk.emplace(-1, INT_MAX); // 下标, 价格
this->idx = -1;
}
int next(int price) {
++idx;
while (price >= stk.top().second){
stk.pop();
}
int res = idx - stk.top().first; // 注意这里的处理
stk.emplace(idx, price);
return res;
}
private:
stack<pair<int, int>> stk;
int idx;
};
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/