1. List History Backward Scan
Intuition
Append each incoming price to a list, then loop backward from the end and count consecutive prices <= current price.
Algorithm
- Step 1: Append
priceto history listprices. - Step 2: Initialize
span = 0. - Step 3: Loop backward from
prices.length - 1down to 0. - Step 4: If
prices[i] <= price, incrementspan. Otherwise, break. - Step 5: Return
span.
#include <iostream>#include <vector> class StockSpanner { std::vector<int> prices;public: StockSpanner() {} int next(int price) { prices.push_back(price); int span = 0; for (int i = (int)prices.size() - 1; i >= 0; i--) { if (prices[i] <= price) { span++; } else { break; } } return span; }}; int main() { StockSpanner spanner; std::vector<int> stream = {100, 80, 60, 70, 60, 75, 85}; std::cout << "Spans: "; for (int p : stream) { std::cout << spanner.next(p) << " "; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) per call, O(N^2) total— On the N-th day, scanning backward through all previous prices takes O(N) operations in the worst case. - Space complexity:
O(N)— O(N) space to store all previous prices in a dynamic list.
Why Brute Force Doesn't Scale:
For 10,000 calls in increasing order, brute force performs ~5 * 107 operations.
Monotonic Stack handles 10,000 queries in <5ms.