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 3bff384

Browse files
author
Sandy
authored
Merge pull request #107 from openset/develop
Add: maximum_subarray
2 parents a5b89ba + 350d144 commit 3bff384

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,16 @@
11
package maximum_subarray
2+
3+
func maxSubArray(nums []int) int {
4+
max, current, l := nums[0], nums[0], len(nums)
5+
for i := 1; i < l; i++ {
6+
if current > 0 {
7+
current += nums[i]
8+
} else {
9+
current = nums[i]
10+
}
11+
if current > max {
12+
max = current
13+
}
14+
}
15+
return max
16+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,23 @@
11
package maximum_subarray
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestMaxSubArray(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{-2, 1, -3, 4, -1, 2, 1, -5, 4},
14+
expected: 6,
15+
},
16+
}
17+
for _, tc := range tests {
18+
output := maxSubArray(tc.input)
19+
if output != tc.expected {
20+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
21+
}
22+
}
23+
}

0 commit comments

Comments
(0)

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