The stock span problem is a financial problem where we have a series of N daily price quotes for a stock and we need to calculate the span of the stock’s price for all N days. The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
[100 80 60 70 60 75 85] – input
1 1 1 2 1 4 6 – output
这道题要求计算每一天股票价格的 stock span,也就是当前价格向左连续有多少天的价格都不高于当天。典型做法是使用单调栈维护一个递减序列:遍历价格时,不断弹出比当前价格小于等于的历史价格,栈顶就能帮助快速定位上一天更高的价格,从而在 O(N) 时间内求出每一天的跨度。示例中价格序列 [100, 80, 60, 70, 60, 75, 85] 的输出为 1 1 1 2 1 4 6,适合考察栈、数组遍历和线性时间优化。