NOTE
Maximum in Sliding Windows
Mirror translation of the original Sword Offer note: Maximum in Sliding Windows.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given an array and a sliding-window size, find the maximum value in every sliding window. For example, for the array {2,3,4,2,6,2,5,1} with window size 3, there are six windows and their maximum values are {4,4,6,6,6,5}. The six windows are: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}. If the window is larger than the array length, return empty.
2. Approach
- Brute force
3. Implementation
3.1. Brute Force
package main
/**
*
* @param num one-dimensional int array
* @param size int
* @return one-dimensional int array
*/
func maxInWindows(num []int, size int) []int {
if size > len(num) || len(num) == 0 || size <= 0 {
return nil
}
res := make([]int, 0)
for i := 0; i < len(num)-size+1; i++ {
currentMax := num[i]
for j := 1; j < size; j++ {
if num[i+j] > currentMax {
currentMax = num[i+j]
}
}
res = append(res, currentMax)
}
return res
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub