Daily Temperatures
LeetCode 739 · View on LeetCode
Monotonic decreasing stack of indices. When a warmer day arrives, pop all cooler days and record the distance.
package main
import "fmt"
func dailyTemperatures(temperatures []int) []int {
result := make([]int, len(temperatures))
stack := []int{} // indices
for i := 0; i < len(temperatures); i++ {
for len(stack) > 0 && temperatures[i] > temperatures[stack[len(stack)-1]] {
idx := stack[len(stack)-1]
stack = stack[:len(stack)-1]
result[idx] = i - idx
}
stack = append(stack, i)
}
return result
}
func main() {
fmt.Println(dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73})) // [1 1 4 2 1 1 0 0]
fmt.Println(dailyTemperatures([]int{30, 40, 50, 60})) // [1 1 1 0]
fmt.Println(dailyTemperatures([]int{60, 50, 40, 30})) // [0 0 0 0]
}