Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#49 from Dharni0607/arrays
Browse files Browse the repository at this point in the history
O(n) solution for maximum contiguos subarray sum
  • Loading branch information
yanglbme authored Jul 27, 2019
2 parents 4ac6264 + 4b7c6e8 commit 76035cd
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions other/maxSubarraySum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/* O(n) solution, for calculating
maximum contiguous sum in the given array. */

package main

import (
"fmt"
)

func Max(x int, y int) int {
if x < y {
return y
}
return x
}

func maxSubarraySum(array []int) int {
var currentMax int = 0
var maxTillNow int = 0
for i := 0; i < len(array); i++ {
currentMax = Max(array[i], currentMax + array[i])
maxTillNow = Max(maxTillNow, currentMax)
}
return maxTillNow
}

func main() {
array := []int{-2, -5, 6, 0, -2, 0, -3, 1, 0, 5, -6}
fmt.Println("Maximum contiguous sum: ", maxSubarraySum(array))
}

0 comments on commit 76035cd

Please sign in to comment.