Skip to content

Commit 76035cd

Browse files
authored
Merge pull request #49 from Dharni0607/arrays
O(n) solution for maximum contiguos subarray sum
2 parents 4ac6264 + 4b7c6e8 commit 76035cd

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

other/maxSubarraySum.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/* O(n) solution, for calculating
2+
maximum contiguous sum in the given array. */
3+
4+
package main
5+
6+
import (
7+
"fmt"
8+
)
9+
10+
func Max(x int, y int) int {
11+
if x < y {
12+
return y
13+
}
14+
return x
15+
}
16+
17+
func maxSubarraySum(array []int) int {
18+
var currentMax int = 0
19+
var maxTillNow int = 0
20+
for i := 0; i < len(array); i++ {
21+
currentMax = Max(array[i], currentMax + array[i])
22+
maxTillNow = Max(maxTillNow, currentMax)
23+
}
24+
return maxTillNow
25+
}
26+
27+
func main() {
28+
array := []int{-2, -5, 6, 0, -2, 0, -3, 1, 0, 5, -6}
29+
fmt.Println("Maximum contiguous sum: ", maxSubarraySum(array))
30+
}

0 commit comments

Comments
 (0)