package main
import (
"fmt"
)
// Print all elements in a slice
func printSlice(arr []int) {
for _, n := range arr {
fmt.Printf("%d ", n)
}
fmt.Println()
}
// Calculate how many days you must wait for a warmer temperature
func numberOfDaysToWait(temperatures []int) []int {
size := len(temperatures)
result := make([]int, size)
stack := make([]int, 0, size) // stack of indices
for i := 0; i < size; i++ {
// While the current temperature is warmer than the temperature
// at the index stored at the top of the stack:
for len(stack) > 0 && temperatures[i] > temperatures[stack[len(stack)-1]] {
index := stack[len(stack)-1] // top
stack = stack[:len(stack)-1] // pop
result[index] = i - index
}
// Push the current index onto the stack
stack = append(stack, i)
}
// Remaining indices in the stack have no warmer future day
// (result already contains zeros)
return result
}
func main() {
temperatures := []int{82, 84, 81, 58, 85, 89, 75, 71}
// 82 -> 84 = 1
// 84 -> 81 -> 58 -> 85 = 3
// 81 -> 58 -> 85 = 2
// 58 -> 85 = 1
// 85 -> 89 = 1
// 89 -> 75 -> 71 = 0
// 75 -> 71 = 0
result := numberOfDaysToWait(temperatures)
printSlice(result)
}
/*
run:
1 3 2 1 1 0 0 0
*/