LeetCode901 Online Stock Plan
classic monotonic stack problem, and this is a monotonic increasing stack.
the problem is a design problem.
//this is a design related problem, it requires us to get the number of days(including current day) that the price is less or requals to current price. the input is dynamic all the time.
//i feels like we need to maintain a monotonic inceasing stack and it's size, but to maintain this monotonic increasing stack requires pop() elements, and this pop will have influence on our next call.
//so each time we push an array in stack, int[2], so int[0] is the value of taday's price, and the int[1] is its 左边最后一个小于等于当前值所拥有的next()结果,这就像是一个递归dp一样,dp[i] = dp[i-1] + 1
class StockSpanner {
Stack<int[]> stack;
public StockSpanner() {
stack = new Stack<>();
}
public int next(int price) {
int res = 0; //keep record of res
while (!stack.isEmpty() && stack.peek()[0] <= price) //pop all the way until current value that larger than current price(就是寻找离当前最近的第一个大于当前值的,在那里停止,就是pop出来所有连续小于等于当前price)
res += stack.pop()[1]; //
res++;
stack.push(new int[]{price, res}); //这句话就是说每个被push进去的都记录了自己前面有多少连续小于自己的
return res;
}
}
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner obj = new StockSpanner();
* int param_1 = obj.next(price);
*/

浙公网安备 33010602011771号