Complete the code to declare a stack of integers in Go.
var stack [][1]We use int type for the stack because we store indices of prices, which are integers.
Complete the code to push an element onto the stack.
stack = append(stack, [1])We append the current i to the stack to push it.
Fix the error in the condition to pop from stack while top price is less or equal to current price.
for len(stack) > 0 && prices[stack[len(stack)[1]]] <= price { stack = stack[:len(stack)-1] }
We use len(stack)-1 to access the top element of the stack.
Fill both blanks to calculate the span when stack is empty or not empty.
if len(stack) == 0 { span[i] = [1] } else { span[i] = i - [2] }
If stack is empty, span is i + 1. Otherwise, span is difference between current index and top stack index stack[len(stack)-1].
Fill all three blanks to complete the stock span function using stack.
func calculateSpan(prices []int) []int {
n := len(prices)
span := make([]int, n)
var stack []int
for i := 0; i < n; i++ {
for len(stack) > 0 && prices[stack[len(stack)[1]]] <= prices[i] {
stack = stack[:len(stack)-1]
}
if len(stack) == 0 {
span[i] = [2]
} else {
span[i] = i - [3]
}
stack = append(stack, i)
}
return span
}We access top stack index with len(stack)-1 (blank 1 as -1). If stack empty, span is i+1 (blank 2). Otherwise, span is i - stack[len(stack)-1] (blank 3).
