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);
     */
    
  • 相关阅读:
    HTML基础02
    HTML基础01
    【springboot中的常用注解】
    【git常用命令】
    【spring使用@Async注解异步处理】
    【let definitions are not supported by current javascript】
    【sql update if else】
    【Tomcat运行时异常:Illegal access: this web application instance has been stopped already.】
    【JAVA float double数据类型保留2位小数点5种方法】
    【MyBatis中大于号以及小于号的表达方式】
  • 原文地址:https://www.cnblogs.com/pk28/p/9613764.html
Copyright © 2011-2022 走看看