901. 股票价格跨度

算法记录

LeetCode 题目:

  编写一个 StockSpanner 类,它收集某些股票的每日报价,并返回该股票当日价格的跨度。



说明

一、题目

  今天股票价格的跨度被定义为股票价格小于或等于今天价格的最大连续日数(从今天开始往回数,包括今天)。
  例如,如果未来7天股票的价格是 [100, 80, 60, 70, 60, 75, 85],那么股票跨度将是 [1, 1, 1, 2, 1, 4, 6]。

二、分析

  • 分析题意可知道需要求解的是当前点之前有多少连续的小于此点的个数.
  • 也就可以变相为求解大于当前的左边第一个索引, 那我们就可以维护一个单调栈来记录第一个大值, 然后利用下标的位移量来判别个数.
class StockSpanner {
    
    
    class Node{
    
    
        public int x;
        public int y;
        public Node(int x, int y) {
    
    
            this.x = x;
            this.y = y;
        }
    }
    private Stack<Node> s;
    private int day;
    public StockSpanner() {
    
    
        s = new Stack();
        s.push(new Node(100000, day++));
    }
    
    public int next(int price) {
    
    
        while(!s.empty() && s.peek().x <= price) s.pop();
        int ret = day - s.peek().y;
        s.push(new Node(price, day++));
        return ret;
    }
}

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

总结

熟悉单调栈的使用。

Guess you like

Origin blog.csdn.net/MTYSYS19990212/article/details/121306922