class StockSpanner:
def __init__(self):
self.stack = [] # Each element is (price, span)
def next(self, price: int) -> int:
span = 1
# Pop prices less than or equal to current and accumulate their spans
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1]
self.stack.append((price, span))
return span
class StockSpanner {
public:
StockSpanner() {}
int next(int price) {
int span = 1;
while (!st.empty() && st.back().first <= price) {
span += st.back().second;
st.pop_back();
}
st.emplace_back(price, span);
return span;
}
private:
std::vector<std::pair<int, int>> st;
};
class StockSpanner {
private Stack<int[]> stack;
public StockSpanner() {
stack = new Stack<>();
}
public int next(int price) {
int span = 1;
while (!stack.isEmpty() && stack.peek()[0] <= price) {
span += stack.pop()[1];
}
stack.push(new int[]{price, span});
return span;
}
}
var StockSpanner = function() {
this.stack = [];
};
StockSpanner.prototype.next = function(price) {
let span = 1;
while (this.stack.length > 0 && this.stack[this.stack.length - 1][0] <= price) {
span += this.stack.pop()[1];
}
this.stack.push([price, span]);
return span;
};
span
of a stock's price on a certain day is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today's price.
You must implement a class (usually named StockSpanner
) with two methods:
StockSpanner()
: Initializes the object.next(price)
: Given the price of the stock for today, returns the span of today's price.next
represents a new day. The input is a sequence of prices, and you must return the span for each price as it arrives. There is only one valid span for each price, and previous prices cannot be reused or revisited except for calculation.
(price, span)
. The stack is strictly decreasing by price from bottom to top.(price, span)
onto the stack.[100, 80, 60, 70, 60, 75, 85]
.
[1, 1, 1, 2, 1, 4, 6]
. This shows how the stack efficiently tracks and compresses spans.
O(n^2)
for n
prices. Space is O(n)
for storing prices.2n
. Thus, time complexity is O(n)
for n
calls to next
. Space complexity is O(n)
for the stack.