|
| 1 | +/** |
| 2 | + * 901. Online Stock Span |
| 3 | + * https://leetcode.com/problems/online-stock-span/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design an algorithm that collects daily price quotes for some stock and returns the |
| 7 | + * span of that stock's price for the current day. |
| 8 | + * |
| 9 | + * The span of the stock's price in one day is the maximum number of consecutive days |
| 10 | + * (starting from that day and going backward) for which the stock price was less than |
| 11 | + * or equal to the price of that day. |
| 12 | + * |
| 13 | + * - For example, if the prices of the stock in the last four days is [7,2,1,2] and the |
| 14 | + * price of the stock today is 2, then the span of today is 4 because starting from |
| 15 | + * today, the price of the stock was less than or equal 2 for 4 consecutive days. |
| 16 | + * |
| 17 | + * - Also, if the prices of the stock in the last four days is [7,34,1,2] and the price |
| 18 | + * of the stock today is 8, then the span of today is 3 because starting from today, |
| 19 | + * the price of the stock was less than or equal 8 for 3 consecutive days. |
| 20 | + * |
| 21 | + * Implement the StockSpanner class: |
| 22 | + * - StockSpanner() Initializes the object of the class. |
| 23 | + * - int next(int price) Returns the span of the stock's price given that today's |
| 24 | + * price is price. |
| 25 | + */ |
| 26 | + |
| 27 | +var StockSpanner = function() { |
| 28 | + this.stack = []; |
| 29 | +}; |
| 30 | + |
| 31 | +/** |
| 32 | + * @param {number} price |
| 33 | + * @return {number} |
| 34 | + */ |
| 35 | +StockSpanner.prototype.next = function(price) { |
| 36 | + let count = 1; |
| 37 | + |
| 38 | + while (this.stack.length && price >= this.stack[this.stack.length - 1][0]) { |
| 39 | + count += this.stack[this.stack.length - 1][1]; |
| 40 | + this.stack.pop(); |
| 41 | + } |
| 42 | + |
| 43 | + this.stack.push([price, count]); |
| 44 | + |
| 45 | + return count; |
| 46 | +}; |
0 commit comments