Daily Temperatures With Monotonic Stack

Solve daily-wait-until-warmer with a monotonic stack of unresolved indexes, settling each in O(1) amortized instead of scanning forward from every day.

GoData Integrity

Code

gosnippet
25 lines
package main

import "fmt"

// dailyTemperatures 返回每天还要等几天才更暖:单调栈保存未决的下标
func dailyTemperatures(temps []int) []int {
	wait := make([]int, len(temps))
	stack := make([]int, 0, len(temps))
	for i, t := range temps {
		// 栈内下标的温度沿栈单调不增;当前更暖就逐个弹出结算
		for len(stack) > 0 && temps[stack[len(stack)-1]] < t {
			top := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			wait[top] = i - top
		}
		stack = append(stack, i)
	}
	return wait
}

func main() {
	fmt.Println(dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73}))
	fmt.Println(dailyTemperatures([]int{30, 30, 31}))
	fmt.Println(dailyTemperatures([]int{40, 39, 38}))
}

Runtime behavior

Everything happens inside the functions dailyTemperatures and main.

The loop for i, t := range temps is the only repeated construct.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature doing the work here: func dailyTemperatures(temps []int) []int

Running the file executes main, which drives dailyTemperatures in order.

Key statements

for i, t := range temps {
	// 栈内下标的温度沿栈单调不增;当前更暖就逐个弹出结算
	for len(stack) > 0 && temps[stack[len(stack)-1]] < t {
		top := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		wait[top] = i - top
	}
	stack = append(stack, i)
}
func main() {
	fmt.Println(dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73}))
	fmt.Println(dailyTemperatures([]int{30, 30, 31}))
	fmt.Println(dailyTemperatures([]int{40, 39, 38}))
}
stack := make([]int, 0, len(temps))

Interactive Tools for This Topic

FAQ

How do you run Daily Temperatures With Monotonic Stack?
Nothing to install first — run the file and the program does the rest.