Sliding Window Maximum Monotonic Deque (Go)
Track window maximums with a monotonic deque of indexes whose values stay decreasing, so each position pops outdated candidates and reads the front.
Code
package main
import "fmt"
// sliding window maximum: a monotonic deque of indexes keeps values decreasing
func maxSlidingWindow(nums []int, k int) []int {
deque := make([]int, 0, k)
result := make([]int, 0, len(nums)-k+1)
for i, v := range nums {
// 队首下标滑出窗口则丢弃
if len(deque) > 0 && deque[0] <= i-k {
deque = deque[1:]
}
// 队尾不大于当前值的候选都不再可能是最大值
for len(deque) > 0 && nums[deque[len(deque)-1]] <= v {
deque = deque[:len(deque)-1]
}
deque = append(deque, i)
if i >= k-1 {
result = append(result, nums[deque[0]])
}
}
return result
}
func main() {
nums := []int{1, 3, -1, -3, 5, 3, 6, 7}
fmt.Println(maxSlidingWindow(nums, 3))
fmt.Println(maxSlidingWindow([]int{9, 8}, 2))
}Sliding Window Maximum Monotonic Deque (Go): what runs and why
Sliding Window Maximum Monotonic Deque (Go) keeps everything in the functions maxSlidingWindow and main.
Iteration happens inside for i, v := range nums — everything outside it runs once.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Putting it to use
Entry signature: func maxSlidingWindow(nums []int, k int) []int
main is the driver: it invokes maxSlidingWindow before returning.
Core lines
func main() {
nums := []int{1, 3, -1, -3, 5, 3, 6, 7}
fmt.Println(maxSlidingWindow(nums, 3))
fmt.Println(maxSlidingWindow([]int{9, 8}, 2))
}
result := make([]int, 0, len(nums)-k+1)
result = append(result, nums[deque[0]])
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Sliding Window Maximum Monotonic Deque (Go)?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.