【LeetCode】901, stock price span

1. The topic

901. Stock Price Span

2. Ideas

Left direction, <= this value, continuous maximum interval.

That is, in the left direction, the first >= this value, the difference between the maximum subscripts.

Since it is the first problem >= this value, it can be solved with a monotonic stack.

Therefore, a monotonically decreasing stack is constructed (decreasing from the bottom of the stack to the top of the stack). recorded on the stack pair<下标,值>. When the new element is >= the top of the stack, pop the stack, and when the new element is pushed onto the stack, record the difference between the index and the top of the stack.

Note the test case below: the third element expects an output of 3, so use >= instead of > in the while:

insert image description here

3. Problem solving

class StockSpanner {
    
    
public:
    StockSpanner() {
    
    
        st.emplace(-1,INT_MAX);
        idx = -1;
    }

    int next(int price) {
    
    
        ++idx;
        while (!st.empty() && price >= st.top().second) {
    
    
            st.pop();
        }
        int ret = idx - st.top().first;
        st.emplace(idx, price);
        return ret;
    }
private:
    stack<pair<int,int>> st;
    int idx;
};

/**
 * 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/jiaoyangwm/article/details/127468571