Kadane Max Subarray Sum
Sweep a slice once with Kadane: reset the running sum when it turns negative, track the best window, and print both the sum and the winning subarray.
Code
package main
import "fmt"
// kadane: single linear scan for the max subarray sum, also returning the window
func kadane(nums []int) (int, int, int) {
best := nums[0]
cur := nums[0]
start, end := 0, 0
anchor := 0
for i := 1; i < len(nums); i++ {
if cur < 0 {
cur = nums[i]
anchor = i
} else {
cur += nums[i]
}
if cur > best {
best = cur
start, end = anchor, i
}
}
return best, start, end
}
func main() {
series := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
sum, start, end := kadane(series)
fmt.Printf("max subarray sum %d over %v\n", sum, series[start:end+1])
}Kadane Max Subarray Sum: inside the code
The snippet is organized around the functions kadane and main.
Iteration happens inside for i := 1; i < len(nums); i++ — everything outside it runs once.
Watch out for
- No third-party code: every API call resolves inside the runtime.
Putting it to use
Entry signature: func kadane(nums []int) (int, int, int)
The demo output is labeled (max subarray sum), so each printed line points back to the operation that produced it.
main sequences kadane; executing the file runs that flow once.
Core lines
func main() {
series := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
sum, start, end := kadane(series)
fmt.Printf("max subarray sum %d over %v\n", sum, series[start:end+1])
}
cur += nums[i]
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Kadane Max Subarray Sum print when run?
- Execute the whole file; each printed line is prefixed with a label like `max subarray sum`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.