Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 901. Online Stock Span

Rain Hu

901. Online Stock Span


一、題目

Design an algorithm that 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 backward) for which the stock price was less than or equal to today’s price.

Example 1:

Constraints:


二、分析

三、解題

1. Monotonic Stack

class StockSpanner {
public:
    stack<pair<int,int>> st;
    int day = 0;        // 記錄第 ith day
    StockSpanner() {
        st.push(make_pair(INT_MAX, -1));    // 令 stack 不會為空
    }
    
    int next(int price) {
        while (st.top().first <= price) st.pop();   // 遇到小於等於的都 pop掉
        int res = day - st.top().second;    // 堆頂的位置與當前位置差即為解
        st.push(make_pair(price, day++));   // 再將當前股價推到堆中
        return res;
    }
};

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1047. Remove All Adjacent Duplicates In String
Next
[LeetCode] 1544. Make The String Great