|
| 1 | +PROBLEM: |
| 2 | + |
| 3 | + |
| 4 | +Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock's price for the |
| 5 | +current day. |
| 6 | +The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backwards) |
| 7 | +for which the price of the stock was less than or equal to today's price. |
| 8 | +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 |
| 9 | +be [1, 1, 1, 2, 1, 4, 6]. |
| 10 | + |
| 11 | + |
| 12 | +Example 1: |
| 13 | +Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]] |
| 14 | +Output: [null,1,1,1,2,1,4,6] |
| 15 | +Explanation: |
| 16 | +First, S = StockSpanner() is initialized. Then: |
| 17 | +S.next(100) is called and returns 1, |
| 18 | +S.next(80) is called and returns 1, |
| 19 | +S.next(60) is called and returns 1, |
| 20 | +S.next(70) is called and returns 2, |
| 21 | +S.next(60) is called and returns 1, |
| 22 | +S.next(75) is called and returns 4, |
| 23 | +S.next(85) is called and returns 6. |
| 24 | + |
| 25 | +Note that (for example) S.next(75) returned 4, because the last 4 prices |
| 26 | +(including today's price of 75) were less than or equal to today's price. |
| 27 | + |
| 28 | + |
| 29 | +Note: |
| 30 | + |
| 31 | +1.Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5. |
| 32 | +2.There will be at most 10000 calls to StockSpanner.next per test case. |
| 33 | +3.There will be at most 150000 calls to StockSpanner.next across all test cases. |
| 34 | +4.The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages. |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +SOLUTION: |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +class StockSpanner { |
| 45 | +private: |
| 46 | + |
| 47 | + stack<pair<int,int>> s; |
| 48 | + int c; |
| 49 | + |
| 50 | +public: |
| 51 | + StockSpanner() { |
| 52 | + c=0; |
| 53 | + } |
| 54 | + |
| 55 | + int next(int price) { |
| 56 | + |
| 57 | + while(!s.empty() && price>=s.top().second) |
| 58 | + { |
| 59 | + s.pop(); |
| 60 | + } |
| 61 | + |
| 62 | + int ans; |
| 63 | + |
| 64 | + if(s.empty()) |
| 65 | + ans = c + 1; |
| 66 | + else |
| 67 | + ans = c - s.top().first; |
| 68 | + |
| 69 | + s.push({c,price}); |
| 70 | + c++; |
| 71 | + |
| 72 | + return ans; |
| 73 | + } |
| 74 | +}; |
| 75 | + |
| 76 | +/** |
| 77 | + * Your StockSpanner object will be instantiated and called as such: |
| 78 | + * StockSpanner* obj = new StockSpanner(); |
| 79 | + * int param_1 = obj->next(price); |
| 80 | + */ |
0 commit comments