# 901.Online Stock Span

**901.Online Stock Span**

题目难度 Medium

> 编写一个 StockSpanner 类，它收集某些股票的每日报价，并返回该股票当日价格的跨度。 今天股票价格的跨度被定义为股票价格小于或等于今天价格的最大连续日数（从今天开始往回数，包括今天）。 例如，如果未来7天股票的价格是 \[100, 80, 60, 70, 60, 75, 85]，那么股票跨度将是 \[1, 1, 1, 2, 1, 4, 6]。

```
示例：

输入：["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
输出：[null,1,1,1,2,1,4,6]
解释：
首先，初始化 S = StockSpanner()，然后：
S.next(100) 被调用并返回 1，
S.next(80) 被调用并返回 1，
S.next(60) 被调用并返回 1，
S.next(70) 被调用并返回 2，
S.next(60) 被调用并返回 1，
S.next(75) 被调用并返回 4，
S.next(85) 被调用并返回 6。

注意 (例如) S.next(75) 返回 4，因为截至今天的最后 4 个价格
(包括今天的价格 75) 小于或等于今天的价格。


提示：

调用 StockSpanner.next(int price) 时，将有 1 <= price <= 10^5。
每个测试用例最多可以调用  10000 次 StockSpanner.next。
在所有测试用例中，最多调用 150000 次 StockSpanner.next。
此问题的总时间限制减少了 50%。
```

方法: 主要问题是超时问题，如果直接用循环一个个比较，最后肯定会超时。方法是新建一个向量，保存之前的跨度。

* 如果当前的价格小于昨天的，则直接返回1；
* 如果当前价格大于等于昨天的，则当前跨度为1加上昨天的跨度，并将索引回朔至昨天跨度的天数。因为在此天数之前的一天价格是大于昨天的，但不一定大于今天，所以继续比较。
* 如果回朔的天数为负值，则直接退出。

```
class StockSpanner {
    vector<int> stock;
    vector<int> step;
public:
    StockSpanner() {
        stock.clear();
        step.clear();

    }

    int next(int price) {
        stock.push_back(price);
        return maxn(price);

    }
int maxn(int p)
{
    int size = stock.size()-1;
    if(size==0) {step.push_back(1); return 1;}
    if(p<stock[size-1])
    {
        step.push_back(1);
        return 1;
    }

    step.push_back(1);
    int tmp=size-1;
    while(p >= stock[tmp])
    {
        step[size] +=step[tmp];
        tmp -= step[tmp];
        if(tmp<0) break;
    }


    return step[size];
}
};

/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner obj = new StockSpanner();
 * int param_1 = obj.next(price);
 */
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/901.online_stock_span.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
