Online Stock Span

Medium#901price and span

Build a class that gets a stock's price one day at a time. Each call next(price) returns today's span: how many days in a row, counting back from today and including it, the price was not higher than today's. Our example: next(7), next(3), next(4), next(4), next(2), next(9) return 1, 1, 2, 3, 1, 6.

input
Calls one after another: StockSpanner() starts, then each next(price) gets the stock’s price for one more day.
returns
next(price) returns today’s span: how many days in a row, counting back from today and including it, the price was not higher than today’s.
constraints
  • 1 ≤ calls of next ≤ 2000
  • 1 ≤ price ≤ 10⁵
our 10 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
var StockSpanner = function() {

};

/**
 * @param {number} price
 * @return {number}
 */
StockSpanner.prototype.next = function(price) {

};

/**
 * Your StockSpanner object will be instantiated and called as such:
 * var obj = new StockSpanner()
 * var param_1 = obj.next(price)
 */
Ctrl ↵
format
reset

saved in this browser

10 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more monotonic stack problems

Pattern “Monotonic stack” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.