Jerry's Blog

Recording what I learned everyday

View on GitHub


25 August 2020

LeetCode(901) -- Online Stock Span

by Jerry Zhang

Problem

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].

Solution

单调栈。一个栈保持递减,另一个栈记录这个数前面比它小的数有几个。

class StockSpanner {
    
    Stack<Integer> prices, weights;

    public StockSpanner() {
        prices = new Stack<>();
        weights = new Stack<>();
    }
    
    public int next(int price) {
        int w = 1;
        while (!prices.isEmpty() && prices.peek() <= price) {
            prices.pop();
            w += weights.pop();
        }
        prices.push(price);
        weights.push(w);
        return w;
    }
}

19.89% 有点慢

The Best Solution

class StockSpanner {
    
    int[] stocks;
    int[] memoize;
    int size;
    public StockSpanner() {
        this.stocks = new int[10000];
        this.memoize = new int[10000];
        this.size=-1;
    }
    
    public int next(int price) {
        int i = this.size;
        int count = 1;
        while (i >=0) {
            if(this.stocks[i] <= price) {
                count += this.memoize[i];
                i -= this.memoize[i];
            } else {
                break;
            }
        }
        this.size++;
        this.stocks[size] = price;
        this.memoize[size] = count;
        return count;
    }
}
tags: LeetCode