Golang 分治法求切片最大子数组

package main

import (
    "fmt"
)

func FIND_MAX(Slice []int,low,mid,high int) (int,int,int){

    left_sum:= -99999
    sum :=0
    max_left:=mid
    for i:=mid ;i >= low ;i-- {
        sum += Slice[i]
        if sum > left_sum{
            left_sum = sum
            max_left = i
        }
    }

    right_sum := -99999
    sum = 0
    max_right := mid+1
    for j:=mid+1 ;j <= high ;j++ {
        sum += Slice[j]
        if sum > right_sum{
            right_sum = sum
            max_right = j
        }
    }
    return max_left,max_right,left_sum+right_sum
}

func Testarray(a []int,low,high int) (int,int,int) {
    max_left:= low
    max_right := high
    sum := 0
    if high == low {
        max_left = low
        max_right = high
        sum = a[low]
    }else {
        mid:=0
        if (high-low+1)%2 ==0 {
            mid = (high+low-1)/2
        }else{
            mid = (high+low)/2
        }

        left_low, left_high, left_sum := Testarray(a, low, mid)
        right_low, right_high, right_sum := Testarray(a, mid+1, high)
        across_left, across_right, across_sum := FIND_MAX(a, low, mid, high)

        if left_sum >= right_sum && left_sum >= across_sum {
            max_left = left_low
            max_right = left_high
            sum = left_sum
        }else if right_sum >= left_sum && right_sum >= across_sum {
            max_left = right_low
            max_right = right_high
            sum = right_sum
        }else{
            max_left= across_left
            max_right = across_right
            sum = across_sum
        }
    }
    return max_left,max_right,sum
}

func main() {
        var Slice []int
        Slice = []int{2, 3, 5, 6, 7, -1, -2, 3, -6, 10, -7, 1}
        low, high, sum := Testarray(Slice, 0, len(Slice)-1)
        fmt.Println(low,high,sum)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值