Complete the code to initialize an empty stack for the stock span problem.
const stack = [1];We use an empty array [] as a stack in JavaScript.
Complete the code to push the current index onto the stack.
stack.[1](i);Use push to add an element to the top of the stack.
Fix the error in the condition to pop from the stack while the current price is higher than the price at the top index of the stack.
while (stack.length > 0 && prices[i] [1] prices[stack[stack.length - 1]]) { stack.pop(); }
We pop while the current price is greater than the price at the top of the stack.
Fill both blanks to calculate the span for the current day correctly.
const span = stack.length === 0 ? [1] : i - stack[[2]];
If the stack is empty, the span is the current day index plus one. Otherwise, it's the difference between current index and the top index on the stack.
Fill all three blanks to complete the stock span function using a stack.
function calculateSpan(prices) {
const n = prices.length;
const span = new Array(n).fill(0);
const stack = [];
for (let i = 0; i < n; i++) {
while (stack.length > 0 && prices[i] [1] prices[stack[stack.length - 1]]) {
stack.[2]();
}
span[i] = stack.length === 0 ? i [3] 1 : i - stack[stack.length - 1];
stack.push(i);
}
return span;
}The function pops from the stack while current price is greater than the price at the top index. It uses pop() to remove indices. The span is calculated by adding 1 to the index if stack is empty.
