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);
     */
    
  • 相关阅读:
    在osg的图形上贴一张纹理图片
    在vs下的osg的qt窗口开发例子以及一些注意事项
    几个排序算法
    UVa11988-破损的键盘 Broken Keyboard
    UVa 442-矩阵链乘 Matrix Chain Multiplication
    Uva 514-铁轨 Rails
    Uva 136-丑数 ugly number
    修改 Sublime 按快捷键 ctrl+s 自动格式化(reindent lines)的问题
    React Native 项目配置 Flow (windows环境)
    Redux-Form 基础使用
  • 原文地址:https://www.cnblogs.com/pk28/p/9613764.html
Copyright © 2011-2022 走看看