Leetcode 901. Online Stock Span
The problem is to design a system for calculating the stock span of each day based on daily stock prices. The stock span is defined as the number of consecutive days leading up to the current day where the stock price was less than or equal to the current day’s price, including the current day itself.
Implement the StockSpanner
class:
StockSpanner()
Initializes the object of the class.int next(int price)
Returns the span of today’s price.Example:
Input:
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output:
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation:
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4
stockSpanner.next(85); // return 6
1 <= price <= 10^5
and there may be up to 10^5
calls to the next
method.next
method should return the stock span for given day’s price.To solve this problem efficiently, we can use a stack to keep track of the stock prices and their corresponding spans. Here is the strategy:
1
plus the sum of spans of all the popped elements.This way, the stack helps us efficiently compute the spans of stock prices in O(1)
average time per call.
#include <stack>
#include <utility>
class StockSpanner {
private:
std::stack<std::pair<int, int>> stockStack; // Pair (price, span)
public:
StockSpanner() {
// Initialize necessary data structures
}
int next(int price) {
int span = 1;
// Calculate span based on previous prices
while (!stockStack.empty() && stockStack.top().first <= price) {
span += stockStack.top().second;
stockStack.pop();
}
// Push the current price and its span onto the stack
stockStack.push({price, span});
return span;
}
};
The time complexity for each next
call is amortized O(1)
. This is because each price is pushed and popped from the stack exactly once, leading to a total time complexity of O(n)
for n
calls to the next
method. Thus, the average time complexity per operation is constant.
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?