Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Stock Span Problem

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.

Implement the StockSpanner class:

monotonic stack

code

class StockSpanner {
    stack<pair<int, int>> st;

public:
    StockSpanner() { }

    int next(int price)
    {
        int count = 1;
        while (!st.empty() && st.top().first <= price) {
            count += st.top().second;
            st.pop();
        }
        st.push({ price, count });
        return count;
    }
};