zoukankan      html  css  js  c++  java
  • leetcode 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].

    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: 
    First, S = StockSpanner() is initialized.  Then:
    S.next(100) is called and returns 1,
    S.next(80) is called and returns 1,
    S.next(60) is called and returns 1,
    S.next(70) is called and returns 2,
    S.next(60) is called and returns 1,
    S.next(75) is called and returns 4,
    S.next(85) is called and returns 6.
    
    Note that (for example) S.next(75) returned 4, because the last 4 prices
    (including today's price of 75) were less than or equal to today's price.
    

    思路:每次插入新值x时,找到前面的比x大的值的位置,那么答案就是当前位置减去那个最大值的位置。 如果没有找到比x大的值,那么就是x的位置减去INT_Max的位置,如下代码实现。

    总时间复杂度是O(len(next))

    class StockSpanner {
    public:
        int id = 0;
        stack<pair<int, int> > s;
        StockSpanner() {
            s.push({INT_MAX, 0});
        }
        
        int next(int price) {
            id++;
            while (!s.empty() && price >= s.top().first) s.pop();
            int begin = s.top().second;
            s.push({price, id});
            return id - begin;
        }
    };
    
    /**
     * Your StockSpanner object will be instantiated and called as such:
     * StockSpanner obj = new StockSpanner();
     * int param_1 = obj.next(price);
     */
    
  • 相关阅读:
    堆排序
    冒泡排序
    描述字符串写入文件
    Java Socket编程,读服务器几个字符,再写入本地显示。
    final,finally,finalize区别
    圆桌问题 (a)
    表达式
    计算系数
    乌龟棋
    显示图像(多源dfs)
  • 原文地址:https://www.cnblogs.com/pk28/p/9613764.html
Copyright © 2011-2022 走看看