LeetCode Solutions
901. Online Stock Span
Time: Space:
class StockSpanner {
public:
int next(int price) {
int span = 1;
while (!stack.empty() && stack.top().first <= price)
span += stack.top().second, stack.pop();
stack.emplace(price, span);
return span;
}
private:
stack<pair<int, int>> stack; // (price, span)
};
class StockSpanner {
public int next(int price) {
int span = 1;
while (!stack.isEmpty() && stack.peek().getKey() <= price)
span += stack.pop().getValue();
stack.push(new Pair<>(price, span));
return span;
}
// (price, span)
private Stack<Pair<Integer, Integer>> stack = new Stack<>();
}
class StockSpanner:
def __init__(self):
self.stack = [] # (price, span)
def next(self, price: int) -> int:
span = 1
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1]
self.stack.append((price, span))
return span