题目:
leetcode.cn/problems/on…
算法:
方法一:单调栈
问题的本质是当前index - 最近一个大于price的值的index
type StockSpanner struct {
stack [][]int // []int{val, index}
index int
}
func Constructor() StockSpanner {
return StockSpanner{
stack: [][]int{[]int{-1, -1}},
}
}
func (this *StockSpanner) Next(price int) int {
i := len(this.stack) - 1
// fmt.Println(this.stack, price, i)
for i >= 1 && this.stack[i][0] <= price {
this.stack = this.stack[:i]
i --
}
this.stack = append(this.stack, []int{price, this.index})
ans := this.index - this.stack[i][1]
this.index ++
return ans
}
/**
* Your StockSpanner object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Next(price);
*/