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 }
|