Skip to content

Instantly share code, notes, and snippets.

@felipernb
Created October 15, 2012 08:39
Show Gist options
  • Save felipernb/3891477 to your computer and use it in GitHub Desktop.
Save felipernb/3891477 to your computer and use it in GitHub Desktop.
Maximum Subarray in Go
func MaxSubarray(a []int) []int {
currentSumStart := 0
currentSum := 0
maxSumStart := 0
maxSumEnd := 0
maxSum := 0
for currentSumEnd := 0; currentSumEnd < len(a); currentSumEnd++ {
currentSum += a[currentSumEnd]
if currentSum > maxSum {
maxSum = currentSum
maxSumStart = currentSumStart
maxSumEnd = currentSumEnd
}
if currentSum < 0 {
currentSumStart = currentSumEnd + 1
currentSum = 0
}
}
return a[maxSumStart : maxSumEnd + 1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment