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

版权声明:一蓑烟雨任平生 https://blog.csdn.net/zhangyexinaisurui/article/details/81592687
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)
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页