less than 1 minute read

Problem Statement

leetcode problem link

My Solution [TLE]

public class StockSpanner {
    private Stack<int> _stack;
    public StockSpanner() {
        _stack = new();
    }

    public int Next(int price) {
        _stack.Push(price);
        Stack<int> temp = new Stack<int>(new Stack<int>(_stack));
        int res = 0;
        while (temp.Count > 0 && temp.Peek() <= price) {
            res++;
            temp.Pop();
        }
        return res;
    }
}

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

Improve Algorithm [Accepted]

public class StockSpanner {
    private Stack<(int, int)> _stack;
    public StockSpanner() {
        _stack = new();
    }

    public int Next(int price) {
        int res = 1;
        while (_stack.Count > 0 && (_stack.Peek()).Item1 <= price) {
            (int currentPrice, int span) = _stack.Pop();
            res += span;
        }
        _stack.Push((price, res));
        return res;
    }
}

Editorial

Approach: Monotonic Stack

class StockSpanner:
    def __init__(self):
        self.stack = []

    def next(self, price: int) -> int:
        ans = 1
        while self.stack and self.stack[-1][0] <= price:
            ans += self.stack.pop()[1]

        self.stack.append([price, ans])
        return ans

# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)