• 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);
     */
    
  • 相关阅读:
    V2热帖:要多健壮的代码才能支撑起千变万化的需求?
    jmeter生成html报告的命令
    jmeter5.x&4.x搭配使用Serveragent 监听服务端性能参数
    springboot关于tomcat的几个默认配置
    nginx日志统计分析-shell
    OpenStack虚拟机VIP配置步骤
    openstack 3.14.3 虚拟机增加指定IP网卡
    OpenStack各组件的常用命令
    Filebeat的Registry文件解读
    一个shell脚本的实践
  • 原文地址:https://www.cnblogs.com/pk28/p/9613764.html
Copyright © 2020-2023  润新知