LeetCode #901 Online Stock Span 股票價格跨度 901 Online Stock Span 股票價格跨度

901 Online Stock Span 股票價格跨度

Description:
Design an algorithm that 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 backward) for which the stock price 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].
Implement the StockSpanner class:

StockSpanner() Initializes the object of the class.
int next(int price) Returns the span of the stock's price given that today's price is price.

Example:

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]

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

Constraints:

1 <= price <= 10^5
At most 10^4 calls will be made to next.

題目描述:
編寫一個 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%。

思路:

模擬
記錄下標的位置
如果下標指向的元素個數小於 n, 則移動下標, 並更新 n
否則減少下標指向的元素個數, 並將 n 置零
返回時比較下標和 encoding 的長度返回 -1 或對應位置的元素
時間複雜度爲 O(n), 空間複雜度爲 O(n)

代碼:
C++:

class StockSpanner 
{
private:
    stack<pair<int, int>> s;
public:
    StockSpanner() {}
    
    int next(int price) 
    {
        int result = 1;
        if (s.empty() or price < s.top().first)
        {
            s.push({ price, result });
            return result;
        }
        while (!s.empty() and price >= s.top().first)
        {
            result += s.top().second;
            s.pop();
        }
        s.push({ price, result });
        return result;
    }
};

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

Java:

class StockSpanner {
    private Stack<Integer> prices, days;

    public StockSpanner() {
        prices = new Stack<>();
        days = new Stack<>();
    }
    
    public int next(int price) {
        int result = 1;
        if (prices.isEmpty() || price < prices.peek()) {
            prices.push(price);
            days.push(result);
            return result;
        }
        while (!prices.isEmpty() && price >= prices.peek()) {
            result += days.pop();
            prices.pop();
        }
        prices.push(price);
        days.push(result);
        return result;
    }
}

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

Python:

class StockSpanner:

    def __init__(self):
        self.stack = []


    def next(self, price: int) -> int:
        result = 1
        if not self.stack or price < self.stack[-1][0]:
            self.stack.append((price, result))
            return result
        while self.stack and price >= self.stack[-1][0]:
            result += self.stack.pop()[1]
        self.stack.append((price, result))
        return result
        


# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章