Skip to content

Commit

Permalink
Merge pull request #108 from vaskoz/day49
Browse files Browse the repository at this point in the history
Day49
  • Loading branch information
vaskoz committed Oct 9, 2018
2 parents 6df2d03 + 5790597 commit 3b8fe7e
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,4 @@ problems from
* [Day 45](https://github.com/vaskoz/dailycodingproblem-go/issues/101)
* [Day 46](https://github.com/vaskoz/dailycodingproblem-go/issues/103)
* [Day 47](https://github.com/vaskoz/dailycodingproblem-go/issues/105)
* [Day 49](https://github.com/vaskoz/dailycodingproblem-go/issues/107)
20 changes: 20 additions & 0 deletions day49/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package day49

// MaxSubArray returns the maximum possible sum of a contiguous sub-array.
// Runs in O(N) time and O(1) space.
func MaxSubArray(arr []int) int {
var maxEndingHere, maxSoFar int
for i := range arr {
maxEndingHere = max(arr[i], maxEndingHere+arr[i])
maxSoFar = max(maxSoFar, maxEndingHere)
}
return maxSoFar
}

// max returns the larger of two ints.
func max(a, b int) int {
if a > b {
return a
}
return b
}
28 changes: 28 additions & 0 deletions day49/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day49

import "testing"

var testcases = []struct {
arr []int
maxSum int
}{
{[]int{34, -50, 42, 14, -5, 86}, 137},
{[]int{-5, -1, -8, -9}, 0},
}

func TestMaxSubArray(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := MaxSubArray(tc.arr); result != tc.maxSum {
t.Errorf("Expected %d got %d", tc.maxSum, result)
}
}
}

func BenchmarkMaxSubArray(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MaxSubArray(tc.arr)
}
}
}

0 comments on commit 3b8fe7e

Please sign in to comment.