题目:
class StockSpanner {
//单调栈,栈底到栈顶是price是递减的
//栈中存储的是价格的索引和价格使用 int[]{index,price} 表示。
Deque<int[]> stack = new LinkedList<>();
int cur = 0;
public int next(int price) {
//将栈顶价格小于price的出栈
while (!stack.isEmpty() && stack.peek()[1] <= price) stack.pop();
//栈为空则该price是最低的,cur是当前元素的索引,减去大于该元素的索引得出ans.
int prev = stack.isEmpty() ? -1 : stack.peek()[0], ans = cur - prev;
//将该价格入栈,并更新索引
stack.push(new int[]{cur++,price});
return ans;
}
}