You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
According to the problem description, we can know that for the price price on a certain day, we need to find the first price that is greater than price when looking back, and the difference between the indices of these two prices is the span of the price on that day.
57
+
58
+
This is actually a classic monotonic stack model, which finds the first element on the left that is greater than the current element.
59
+
60
+
We maintain a stack that is monotonically decreasing from the bottom to the top in terms of prices. Each element in the stack stores a pair of $(price, cnt)$, where $price$ represents the price, and $cnt$ represents the span of the current price.
61
+
62
+
When encountering a price $price$, we compare it with the top element of the stack. If the price of the top element of the stack is less than or equal to price, we add the span cnt of the current price to the span of the top element of the stack, and then pop the top element of the stack until the price of the top element of the stack is greater than price, or the stack is empty.
63
+
64
+
Finally, we push $(price, cnt)$ onto the stack and return $cnt$.
65
+
66
+
The time complexity is $O(n)$, where $n$ is the number of calls to the next function.
67
+
54
68
<!-- tabs:start -->
55
69
56
70
### **Python3**
@@ -113,7 +127,7 @@ public:
113
127
cnt += stk.top().second;
114
128
stk.pop();
115
129
}
116
-
stk.push({price, cnt});
130
+
stk.emplace(price, cnt);
117
131
return cnt;
118
132
}
119
133
@@ -162,19 +176,19 @@ type pair struct{ price, cnt int }
162
176
163
177
```ts
164
178
classStockSpanner {
165
-
privatestack: [number, number][];
179
+
privatestk:number[][];
166
180
167
181
constructor() {
168
-
this.stack= [[Infinity, -1]];
182
+
this.stk= [];
169
183
}
170
184
171
185
next(price:number):number {
172
-
letres=1;
173
-
while (this.stack[this.stack.length-1][0] <=price) {
174
-
res+=this.stack.pop()[1];
186
+
letcnt=1;
187
+
while (this.stk.length&&this.stk.at(-1)[0] <=price) {
0 commit comments