package mainimport ( "fmt")//求最大子序列和(如果都是正数,当然是全局相加和,问题在于怎么排除负数)func maxSum(arr []int) int { arrlen := len(arr) maxSum := arr[0] //两个辅助变量 maxSum和tempSum tempSum := 0 for i := 0; i < arrlen; i++ { tempSum += arr[i] if tempSum > maxSum { maxSum = tempSum } else if tempSum < 0 { //关键就是这货 tempSum = 0 } } return maxSum}func main() { var arr = []int{5, -66, 1, -8, -9} fmt.Printf("max arr sum is %d \n", maxSum(arr))}
输出内容:max arr sum is 5