Drill

ProblemsGo › data

The peak in each window

harddataSliding windowArraysGo

A monitoring chart smooths readings by asking, for each fixed-size window, what the loudest moment inside it was.

windowMax(values: list<int>, window: int) → list<int>

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func windowMax(values []int, window int) []int {
	
}

Worked examples

CallResult
windowMax([]int{1, 3, 2, 5}, 2)[]int{3, 3, 5}
windowMax([]int{1, 2, 3}, 3)[]int{3}
windowMax([]int{5}, 1)[]int{5}
windowMax([]int{4, 1, 3}, 2)[]int{4, 3}

Hint

For each starting index take the maximum of the next `window` values with an inner loop.

Reference solution in Go
func windowMax(values []int, window int) []int {
	result := []int{}
	if window <= 0 || window > len(values) {
		return result
	}
	for i := 0; i+window <= len(values); i++ {
		m := values[i]
		for j := i + 1; j < i+window; j++ {
			if values[j] > m {
				m = values[j]
			}
		}
		result = append(result, m)
	}
	return result
}

The same problem in another language

More data problems in Go