1
var StockSpanner = function () {
2
this.stack = [];
3
this.idx = 0;
4
};
5

6
StockSpanner.prototype.next = function (price) {
7
// keep Pop-ing if top element of stack is bigger than current price
8
while (
9
this.stack.length > 0 &&
10
this.stack[this.stack.length - 1][0] <= price
11
) {
12
this.stack.pop();
13
}
14

15
// if stack is empty after above operation
16
if (this.stack.length === 0) {
17
// Push current price with index
18
this.stack.push([price, this.idx]);
19

20
// increment index - this is a tricky part
21
this.idx++;
22

23
return this.idx;
24
}
25

26
// caclulate distance from top element of stack and return
27

28
const res = this.idx - this.stack[this.stack.length - 1][1];
29
this.stack.push([price, this.idx]);
30
this.idx++;
31
return res;
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0