Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0d469ce

Browse files
author
Shuo
authored
Merge pull request #233 from openset/develop
Add: Maximum Average Subarray I
2 parents da6b0e3 + ba05c26 commit 0d469ce

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,17 @@
11
package maximum_average_subarray_i
2+
3+
func findMaxAverage(nums []int, k int) float64 {
4+
max, sum := 0, 0
5+
for i, v := range nums {
6+
sum += v
7+
if i == k-1 {
8+
max = sum
9+
} else if i >= k {
10+
sum -= nums[i-k]
11+
}
12+
if sum > max {
13+
max = sum
14+
}
15+
}
16+
return float64(max) / float64(k)
17+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,25 @@
11
package maximum_average_subarray_i
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
nums []int
7+
k int
8+
expected float64
9+
}
10+
11+
func TestFindMaxAverage(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
nums: []int{1, 12, -5, -6, 50, 3},
15+
k: 4,
16+
expected: 12.75,
17+
},
18+
}
19+
for _, tc := range tests {
20+
output := findMaxAverage(tc.nums, tc.k)
21+
if output != tc.expected {
22+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.nums, tc.k, output, tc.expected)
23+
}
24+
}
25+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /