Leetcode 901. Online Stock Span
Design a data structure that will be used to record a sequence of stock prices, and it should support the following operations:
next(int price)
:
The span of the stock’s price on a given day is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today’s price.
For example, if the stock price is recorded as [100, 80, 60, 70, 60, 75, 85]
, then the spans are [1, 1, 1, 2, 1, 4, 6]
.
next
?
next
call as it will be invoked frequently.To efficiently compute the span, we can utilize a stack to keep track of the stock prices and their corresponding spans. Here’s the strategy in detail:
(price, span)
.1
(since at least the current day is included).import java.util.Stack;
class StockSpanner {
private Stack<int[]> stack; // Stack to store pairs of (price, span)
public StockSpanner() {
stack = new Stack<>();
}
public int next(int price) {
int span = 1;
// Calculate the span for the current price
while (!stack.isEmpty() && stack.peek()[0] <= price) {
span += stack.pop()[1];
}
// Push the current price and its span onto the stack
stack.push(new int[] {price, span});
return span;
}
}
next
function runs in O(1) average time per call.Thus, the amortized time complexity of each next
call is O(1).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?