Skip to content

Commit 4c8dc1b

Browse files
committed
maximum_average_subarray_i_643: solved
1 parent 527b118 commit 4c8dc1b

File tree

6 files changed

+72
-3
lines changed

6 files changed

+72
-3
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 643. Maximum Average Subarray I
2+
3+
https://leetcode.com/problems/maximum-average-subarray-i/description/
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package maximum_average_subarray_i_643
2+
3+
import "math"
4+
5+
func findMaxAverage(nums []int, k int) float64 {
6+
start := 0
7+
end := k - 1
8+
sum := 0.0
9+
10+
for i := start; i <= end; i++ {
11+
sum += float64(nums[i])
12+
}
13+
14+
maxAvg := sum / float64(k)
15+
for end < len(nums)-1 {
16+
sum -= float64(nums[start])
17+
sum += float64(nums[end+1])
18+
maxAvg = math.Max(maxAvg, sum/float64(k))
19+
start++
20+
end++
21+
}
22+
23+
return maxAvg
24+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package maximum_average_subarray_i_643
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test_findMaxAverage(t *testing.T) {
10+
type args struct {
11+
nums []int
12+
k int
13+
}
14+
tests := []struct {
15+
name string
16+
args args
17+
want float64
18+
}{
19+
{
20+
name: "many numbers",
21+
args: args{
22+
nums: []int{1, 12, -5, -6, 50, 3},
23+
k: 4,
24+
},
25+
want: 12.75000,
26+
},
27+
{
28+
name: "single number",
29+
args: args{
30+
nums: []int{5},
31+
k: 1,
32+
},
33+
want: 5.00000,
34+
},
35+
}
36+
for _, tt := range tests {
37+
t.Run(tt.name, func(t *testing.T) {
38+
assert.Equal(t, tt.want, findMaxAverage(tt.args.nums, tt.args.k))
39+
})
40+
}
41+
}

merge_strings_alternately_1768/solution.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package add_two_numbers_2
1+
package merge_strings_alternately_1768
22

33
func mergeAlternately(word1 string, word2 string) string {
44
var (

merge_strings_alternately_1768/solution_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package add_two_numbers_2
1+
package merge_strings_alternately_1768
22

33
import (
44
"testing"

move_zeroes_283/solution_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
package move_zeroes_283
22

33
import (
4-
"github.com/stretchr/testify/assert"
54
"testing"
5+
6+
"github.com/stretchr/testify/assert"
67
)
78

89
func Test_moveZeroes(t *testing.T) {

0 commit comments

Comments
 (0)