Skip to content

Commit 2993e0f

Browse files
committed
feat: Add continuousmax task.
1 parent 90e96cd commit 2993e0f

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

continuousmax/documentation.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// Package continuousmax implements a function to calculate the maximum value
2+
// of a sliding window over a slice of integers.
3+
package continuousmax

continuousmax/get_max.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package continuousmax
2+
3+
import (
4+
"errors"
5+
)
6+
7+
func GetMax(values []int, k int) ([]int, error) {
8+
if len(values) == 0 {
9+
return []int{}, nil
10+
}
11+
if k <= 0 {
12+
return nil, errors.New("k must be greater than 0")
13+
}
14+
if k > len(values) {
15+
return nil, errors.New("k must be less than or equal to the length of values")
16+
}
17+
18+
maxValues := make([]int, 0, len(values)-k+1)
19+
20+
var window []int
21+
for i := 0; i < len(values); i++ {
22+
if len(window) > 0 && window[0] <= i-k {
23+
window = window[1:]
24+
}
25+
26+
for len(window) > 0 && values[window[len(window)-1]] <= values[i] {
27+
window = window[:len(window)-1]
28+
}
29+
30+
window = append(window, i)
31+
32+
if i >= k-1 {
33+
maxValues = append(maxValues, values[window[0]])
34+
}
35+
}
36+
37+
return maxValues, nil
38+
}

continuousmax/get_max_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package continuousmax_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
"github.com/thenativeweb/codingcircle/continuousmax"
8+
)
9+
10+
func TestGetMax(t *testing.T) {
11+
values := []int{27, 9, 17, 2, 12, 8}
12+
windowSize := 3
13+
14+
maxValues, err := continuousmax.GetMax(values, windowSize)
15+
16+
assert.NoError(t, err)
17+
assert.Equal(t, []int{27, 17, 17, 12}, maxValues)
18+
}

0 commit comments

Comments
 (0)