forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum_of_sub_arrays.go
40 lines (32 loc) · 912 Bytes
/
maximum_of_sub_arrays.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package queue
import (
"container/list"
"errors"
)
// ErrQueueEmpty occurs when popping an empty stack.
var ErrQueueEmpty = errors.New("empty queue")
// MaxOfKLengthSubArrays solves the problem in O(n) time and O(k) space.
func MaxOfKLengthSubArrays(numbers []int, k int) ([]int, error) {
output := []int{}
queue := list.New()
var i int
for i = 0; i < k; i++ {
for queue.Len() != 0 && numbers[i] >= numbers[queue.Back().Value.(int)] {
queue.Remove(queue.Back())
}
queue.PushBack(i)
}
for i < len(numbers) {
output = append(output, numbers[queue.Front().Value.(int)])
for queue.Len() != 0 && queue.Front().Value.(int) <= i-k {
queue.Remove(queue.Front())
}
for queue.Len() != 0 && numbers[i] >= numbers[queue.Back().Value.(int)] {
queue.Remove(queue.Back())
}
queue.PushBack(i)
i++
}
output = append(output, numbers[queue.Front().Value.(int)])
return output, nil
}