|
| 1 | +/* |
| 2 | +Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock's price for the current day. |
| 3 | +
|
| 4 | +The span of the stock's price today 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. |
| 5 | +
|
| 6 | +For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6]. |
| 7 | +
|
| 8 | + |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]] |
| 13 | +Output: [null,1,1,1,2,1,4,6] |
| 14 | +Explanation: |
| 15 | +First, S = StockSpanner() is initialized. Then: |
| 16 | +S.next(100) is called and returns 1, |
| 17 | +S.next(80) is called and returns 1, |
| 18 | +S.next(60) is called and returns 1, |
| 19 | +S.next(70) is called and returns 2, |
| 20 | +S.next(60) is called and returns 1, |
| 21 | +S.next(75) is called and returns 4, |
| 22 | +S.next(85) is called and returns 6. |
| 23 | +
|
| 24 | +Note that (for example) S.next(75) returned 4, because the last 4 prices |
| 25 | +(including today's price of 75) were less than or equal to today's price. |
| 26 | + |
| 27 | +
|
| 28 | +Note: |
| 29 | +
|
| 30 | +Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5. |
| 31 | +There will be at most 10000 calls to StockSpanner.next per test case. |
| 32 | +There will be at most 150000 calls to StockSpanner.next across all test cases. |
| 33 | +The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages. |
| 34 | +
|
| 35 | +来源:力扣(LeetCode) |
| 36 | +链接:https://leetcode-cn.com/problems/online-stock-span |
| 37 | +著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 |
| 38 | +*/ |
| 39 | + |
| 40 | +/* O(N) in time and O(N) in space */ |
| 41 | +#include <stack> |
| 42 | +using namespace std; |
| 43 | + |
| 44 | +class StockSpanner { |
| 45 | +private: |
| 46 | + int i; |
| 47 | + stack<int> s, l; |
| 48 | +public: |
| 49 | + StockSpanner() { |
| 50 | + i = -1; |
| 51 | + } |
| 52 | + |
| 53 | + int next(int price) { |
| 54 | + ++i; |
| 55 | + int res; |
| 56 | + |
| 57 | + while( (!s.empty())&&(s.top()<=price) ){ |
| 58 | + s.pop(); |
| 59 | + l.pop(); |
| 60 | + } |
| 61 | + if(s.empty()) res = i + 1; |
| 62 | + else res = i - l.top(); |
| 63 | + |
| 64 | + s.push(price); |
| 65 | + l.push(i); |
| 66 | + return res; |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +/** |
| 71 | + * Your StockSpanner object will be instantiated and called as such: |
| 72 | + * StockSpanner* obj = new StockSpanner(); |
| 73 | + * int param_1 = obj->next(price); |
| 74 | + */ |
0 commit comments