Skip to content

Commit 69f20c3

Browse files
committed
add max sum subvector - scanning algorithm
1 parent 28484de commit 69f20c3

File tree

5 files changed

+60
-1
lines changed

5 files changed

+60
-1
lines changed

column7-back-envelope/square-root-perf/square-root_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99
goth "github.com/LuigiAndrea/test-helper/messages"
1010
)
1111

12-
var steps int = 1000000000
12+
var steps int = 10000000
1313

1414
func TestCallSquareRoot(t *testing.T) {
1515
defer utilities.Elapse(goth.GetFuncName(squareRoot))()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The input is a vector x of n floating-point numbers; the output is the maximum sum found in any contiguous subvector of the input. When all inputs are negative the maximum sub-vector is the empty vector, which has sum zero
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package maxsubvector
2+
3+
import "github.com/LuigiAndrea/GoPearls/utilities"
4+
5+
func maxSubvector(vector []float64) (maxsofar float64) {
6+
n := len(vector)
7+
maxFromZeroToHere := 0.0
8+
for i := 0; i < n; i++ {
9+
maxFromZeroToHere = utilities.Max(maxFromZeroToHere+vector[i], 0)
10+
maxsofar = utilities.Max(maxsofar, maxFromZeroToHere)
11+
}
12+
13+
return
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// +build all column8 maxsubvector
2+
3+
package maxsubvector
4+
5+
import (
6+
"testing"
7+
8+
a "github.com/LuigiAndrea/test-helper/assertions"
9+
m "github.com/LuigiAndrea/test-helper/messages"
10+
)
11+
12+
type testData struct {
13+
vector []float64
14+
expectedValue float64
15+
}
16+
17+
func TestMaxSubVector(t *testing.T) {
18+
19+
tests := []testData{
20+
testData{vector: []float64{-2.4, 8, 3.3, -5.1, 2, -13}, expectedValue: 11.3},
21+
testData{vector: []float64{-2.4, -5.1, -13}, expectedValue: 0},
22+
testData{vector: []float64{2.4, -5.1, 13}, expectedValue: 13},
23+
testData{vector: []float64{2.4, -1.1, 13}, expectedValue: 14.3},
24+
testData{vector: []float64{}, expectedValue: 0},
25+
testData{vector: nil, expectedValue: 0},
26+
}
27+
28+
for i, test := range tests {
29+
if err := a.AssertDeepEqual(test.expectedValue, maxSubvector(test.vector)); err != nil {
30+
t.Error(m.ErrorMessageTestCount(i+1, err))
31+
}
32+
}
33+
}

utilities/helper.go

+11
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,14 @@ func Elapse(name string) func() {
3737
fmt.Printf("%s took %v\n", name, time.Since(start))
3838
}
3939
}
40+
41+
//Max calculate the max element in the parameters list
42+
func Max(elements ...float64) float64 {
43+
maxElement := 0.0
44+
for _, el := range elements {
45+
if el > maxElement {
46+
maxElement = el
47+
}
48+
}
49+
return maxElement
50+
}

0 commit comments

Comments
 (0)