|
| 1 | +# 901. Online Stock Span |
| 2 | + |
| 3 | +Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the |
| 4 | +current day. |
| 5 | + |
| 6 | +The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going |
| 7 | +backward) for which the stock price was less than or equal to the price of that day. |
| 8 | + |
| 9 | +- For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, |
| 10 | + then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` |
| 11 | + consecutive days. |
| 12 | +- Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then |
| 13 | + the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` |
| 14 | + consecutive days. |
| 15 | + |
| 16 | +Implement the StockSpanner class: |
| 17 | + |
| 18 | +- `StockSpanner()` Initializes the object of the class. |
| 19 | +- `int next(int price)` Returns the span of the stock's price given that today's price is `price`. |
| 20 | + |
| 21 | +Example 1: |
| 22 | + |
| 23 | +Input |
| 24 | +["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] |
| 25 | +[[], [100], [80], [60], [70], [60], [75], [85]] |
| 26 | +Output |
| 27 | +[null, 1, 1, 1, 2, 1, 4, 6] |
| 28 | + |
| 29 | +Explanation |
| 30 | +StockSpanner stockSpanner = new StockSpanner(); |
| 31 | +stockSpanner.next(100); // return 1 |
| 32 | +stockSpanner.next(80); // return 1 |
| 33 | +stockSpanner.next(60); // return 1 |
| 34 | +stockSpanner.next(70); // return 2 |
| 35 | +stockSpanner.next(60); // return 1 |
| 36 | +stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to |
| 37 | +today's price. |
| 38 | +stockSpanner.next(85); // return 6 |
| 39 | + |
| 40 | +Constraints: |
| 41 | + |
| 42 | +- `1 <= price <= 10^5` |
| 43 | +- At most `10^4` calls will be made to `next`. |
0 commit comments