在Go(Golang)中找出最大的子阵列的程序

75 阅读1分钟

概述

目的是在一个给定的输入阵列中找到最大的子阵列。该子数组应该是连续的,并且至少包含一个元素

比如说

Input: [4, 5 ,-3]
Maximum Subarray is [4, 5]
Output: 9

另一个例子

Input: [1, 2, -4, 4, 1]
Maximum Subarray is [4, 1]
Output: 5

我们在这里使用Kadane算法。在Kadane算法中,我们保留两个变量maxcurrentMax

  • max 被初始化为IntMin,currentMax被初始化为0

  • 然后我们对数组中的每个元素进行循环运算

    • currentMax=currentMax+ a[i]。
    • 如果currentMax>max,那么max被设置为currentMax
    • 如果currentMax小于零,那么currentMax被重置为零

程序

以下是相同的程序

package main

import "fmt"

const (
	UintSize = 32 << (^uint(0) >> 32 & 1)
	MaxInt   = 1<<(UintSize-1) - 1 // 1<<31 - 1 or 1<<63 - 1
	MinInt   = -MaxInt - 1
)

func main() {
	input := []int{4, 5, -3}
	output := maxSubArray(input)
	fmt.Println(output)

	input = []int{1, 2, -4, 4, 1}
	output = maxSubArray(input)
	fmt.Println(output)
}

func maxSubArray(nums []int) int {
	lenNums := len(nums)

	currentMax := 0
	max := MinInt
	for i := 0; i < lenNums; i++ {
		currentMax = currentMax + nums[i]
		if currentMax > max {
			max = currentMax
		}

		if currentMax < 0 {
			currentMax = 0
		}

	}
	return max
}

输出

9
5