Created
February 1, 2019 12:22
-
-
Save vedhavyas/dde1cf0361f52d9e1bcf4b8169b45299 to your computer and use it in GitHub Desktop.
Kadane's algorithm to find max subarray
This file contains hidden or 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
package main | |
import "fmt" | |
func kadanes(d []int) int { | |
var lm, gm int | |
var init bool | |
for _, n := range d { | |
lm = max(n, n+lm) | |
if !init || lm > gm { | |
gm = lm | |
init = true | |
} | |
} | |
return gm | |
} | |
func max(a, b int) int { | |
if a > b { | |
return a | |
} | |
return b | |
} | |
func main() { | |
fmt.Println(kadanes([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment