901. Online Stock Span

T: O(stack size), depends on next times and ...
S: O(stack size)
class StockSpanner {

    Deque<Integer[]> stack;
    int curr = 0;
    public StockSpanner() {
        stack = new ArrayDeque<>();
    }
    
    public int next(int price) {
        int span = 1;
        while (!stack.isEmpty() && price >= stack.peek()[0]) {
            span += stack.peek()[1];
            stack.pop();
        }
        stack.push(new Integer[] {price, span});
        return span;
    }
}

/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner obj = new StockSpanner();
 * int param_1 = obj.next(price);
 
 maximum number of consecutive days 
 
 for which the stock price was less than or equal to today's price.
 
     .                <- need consecutive smaller or equal
   1  1   1  2  1  4  6
 [100,80,60,70,60,75,85], 
 then the stock spans would be [1,1,1,2,1,4,6].


60. 1 
80. 1
100 1



70  2
       pop 60. 1 
80. 1
100 1



75  => pop 60 70, 1+1+2 = 4
60. 1
70  2
80. 1
100 1


75 4
80 1
100 1


85. => pop 75, 80, so. 1+ 4 +1 = 6
75 4
80 1
100 1


T: O(stack size), depends on next times and ...
S: O(stack size)
 */ja

Last updated