Created
October 15, 2012 08:39
-
-
Save felipernb/3891477 to your computer and use it in GitHub Desktop.
Maximum Subarray in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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