underwindfall / Algorithme

练习总结算法的地方
https://qifanyang.com/resume
1 stars 0 forks source link

OnlineStockSpan901 #317

Open underwindfall opened 2 years ago

underwindfall commented 2 years ago
// time O(n)
    // space O(n)
    class MonotonicStack {
        Stack<Integer> prices, weights;

        public MonotonicStack() {
            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;
        }
    }