#901

Online Stock Span

pupil · 580 · lc medium +29 · 68.8% accepted · 7,203 likes · top 76%

Description

Build an online algorithm that ingests a daily stock price and computes that day's span — the maximum number of consecutive days ending today (today included) for which the price was at most today's price.

Implement the StockSpanner class:

- StockSpanner() initializes the spanner.

- int next(int price) processes today's price and returns its span.

Example 1:

Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]

Example 2:

Explanation
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

1
2
3
4
5
6
7
8
9
10
11
12