分治策略,求最大子数组的和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 //含中间元素,交叉最大
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值