Sponsored
Sponsored
This approach utilizes a stack to track the prices and their corresponding spans. For each new price, we compare it with the top of the stack, which holds the last price and its span. If the new price is higher or equal, we pop from the stack and add the span of the popped element to the current span count. This way, we efficiently calculate the span while ensuring that older prices do not need to be recalculated unnecessarily.
Time Complexity: O(n), where n is the number of calls to next() because each element is pushed and popped from the stack at most once.
Space Complexity: O(n) for storing the stack.
1class StockSpanner:
2 def __init__(self):
3 self.stack = [] # Each element is a tuple (price, span)
4
5 def next(self, price: int) -> int:
6 span = 1
7 # Compare price with elements in stack
8 while self.stack and self.stack[-1][0] <= price:
9 span += self.stack.pop()[1]
10 self.stack.append((price, span))
11 return span
The Python solution uses a list as a stack to store pairs of prices and their spans. For each new price, we initialize the span to 1 and add it to the span of any previous prices from which it is greater or equal, thus ensuring we only process each element once as they are popped from the stack. This makes it efficient for handling up to 10,000 calls.
This approach optimizes memory and simplifies the logic by storing prices along with pre-calculated spans in a tuple or similar structure. This implementation minimizes redundant span computation by leveraging tuple structures efficiently, ideal for platforms that can handle tuple operations swiftly.
Time Complexity: O(n), as each element is only processed once.
Space Complexity: O(n), where n is the number of calls, due to stack storage.
1public class StockSpanner {
2 private Stack<(int price, int span)> stack;
3
4 public StockSpanner() {
5 stack = new Stack<(int, int)>();
}
public int Next(int price) {
int span = 1;
while (stack.Count > 0 && stack.Peek().price <= price) {
span += stack.Pop().span;
}
stack.Push((price, span));
return span;
}
}
The C# solution uses a Stack of tuples (int price, int span) to manage the history of prices and their spans. For each new price, we look at the items in the stack and pop out any elements from the top where the price is lower or equal to the current price, adding their spans to the current span. After processing, the tuple with the current price and computed span is pushed onto the stack.