Class StockSpanner

java.lang.Object
g0901_1000.s0901_online_stock_span.StockSpanner

public class StockSpanner extends Object
901 - Online Stock Span.<p>Medium</p> <p>Design an algorithm that collects daily price quotes for some stock and returns <strong>the span</strong> of that stock&rsquo;s price for the current day.</p> <p>The <strong>span</strong> of the stock&rsquo;s price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today&rsquo;s price.</p> <ul> <li>For example, if the price of a stock over the next <code>7</code> days were <code>[100,80,60,70,60,75,85]</code>, then the stock spans would be <code>[1,1,1,2,1,4,6]</code>.</li> </ul> <p>Implement the <code>StockSpanner</code> class:</p> <ul> <li><code>StockSpanner()</code> Initializes the object of the class.</li> <li><code>int next(int price)</code> Returns the <strong>span</strong> of the stock&rsquo;s price given that today&rsquo;s price is <code>price</code>.</li> </ul> <p><strong>Example 1:</strong></p> <p><strong>Input</strong></p> <p>[&ldquo;StockSpanner&rdquo;, &ldquo;next&rdquo;, &ldquo;next&rdquo;, &ldquo;next&rdquo;, &ldquo;next&rdquo;, &ldquo;next&rdquo;, &ldquo;next&rdquo;, &ldquo;next&rdquo;]</p> <p>[ [], [100], [80], [60], [70], [60], [75], [85]]</p> <p><strong>Output:</strong> [null, 1, 1, 1, 2, 1, 4, 6]</p> <p><strong>Explanation:</strong></p> <pre><code> 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, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= price <= 10<sup>5</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li> </ul>
  • Constructor Details

    • StockSpanner

      public StockSpanner()
  • Method Details

    • next

      public int next(int price)