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.

GoData Integrity

Code

gosnippet
30 lines
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

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`.