[LeetCode] Online Stock Span

901. Online Stock Span

Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock’s price for the current day.

The span of the stock’s price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today’s price.

For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class StockSpanner {
vector<pair<int, int>> v;
public:
StockSpanner() {

}

int next(int price) {
int day = 1, pos = v.size() - 1;
while(pos >= 0) {
if(v[pos].first > price) break;
day += v[pos].second;
pos -= v[pos].second;
}
v.push_back({price,day});
return day;
}
};

/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/online-stock-span/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.