53. 最大子数组和

53. 最大子数组和

解法一: 动态规划

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func maxSubArray(nums []int) int {
ans := nums[0]
pre := nums[0]
for _, num := range nums[1:] {
pre = max(pre + num, num)
ans = max(ans, pre)
}
return ans
}

func max(num1, num2 int) int {
if num1 >= num2 {
return num1
}
return num2
}

解法二: 分治法

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func maxSubArray(nums []int) int {
return dfs(nums, 0, len(nums) - 1)
}

func dfs(nums []int, left int, right int) int {
if left == right {
return nums[left]
}
mid := ((right - left) >> 1) + left
leftSum := dfs(nums, left, mid)
rightSum := dfs(nums, mid + 1, right)
midSum := calcMidSubArray(nums, left, right, mid)
return max(leftSum, max(rightSum, midSum))
}

func calcMidSubArray(nums []int, left, right, mid int) int {
leftSum := -1000000000
sum := 0
for i := mid; i >= left; i-- {
sum += nums[i]
if sum > leftSum {
leftSum = sum
}
}

rightSum := -1000000000
sum = 0
for i := mid + 1; i <= right; i++ {
sum += nums[i]
if sum > rightSum {
rightSum = sum
}
}

return leftSum + rightSum
}

func max(num1, num2 int) int {
if num1 >= num2 {
return num1
}
return num2
}
作者

wuhunyu

发布于

2023-11-20

更新于

2023-11-20

许可协议