分治策略,求最大子数组的和golang实现

package main

import (
   "fmt"
)

func main() {
   a := []int{9, 6, -7, 1, 8, -20, 5, 3, 4, 0, 2}
   l, r, s := FindMaxSubArray(a, 0, 10)
   fmt.Println("max sum:", s)
   fmt.Println("l,r loc:", l, r)
}
func FindMaxCrossArray(a []int, left, mid, right int) (int, int, int) {
   left_sum := 0
   max_left_sum := 0
   var max_left int
   for i := mid; i >= left; i-- {
      left_sum += a[i]
      if left_sum > max_left_sum {
         max_left_sum = left_sum
         max_left = i
      }
   }

   right_sum := 0
   max_right_sum := 0
   var max_right int
   for j := mid + 1; j <= right; j++ {
      right_sum += a[j]
      if right_sum > max_right_sum {
         max_right_sum = right_sum
         max_right = j
      }
   }

   return max_left, max_right, max_left_sum + max_right_sum
}

func FindMaxSubArray(a []int, low, high int) (int, int, int) {
   var left_sum, right_sum, cross_sum int

   var left_low, left_high, right_low, right_high, cross_low, cross_high int

   if low == high { //仅一个元素
      return low, high, a[low]
   } else {
      mid := (low + high) / 2
      left_low, left_high, left_sum = FindMaxSubArray(a, low, mid)
      right_low, right_high, right_sum = FindMaxSubArray(a, mid+1, high)
      cross_low, cross_high, cross_sum = FindMaxCrossArray(a, low, mid, high)
   }

   if left_sum >= right_sum && left_sum >= cross_sum { //左半边最大,返回左半边下标
      return left_low, left_high, left_sum
   } else if right_sum >= left_sum && right_sum >= cross_sum { //右半边最大,返回右半边下标
      return right_low, right_high, right_sum
   }

   return cross_low, cross_high, cross_sum //含中间元素,交叉最大
}

你可能感兴趣的:(golang,算法)