[LeetCode By Go 77]53. Maximum Subarray

题目

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],the contiguous subarray [4,-1,2,1] has the largest sum = 6.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

解题思路

典型的动态规划问题:
定义子问题:tmpSum[i]为以第i个元素结尾的最大连续子数组和
很显然在for循环遍历的过程中,只有两种情况:
1)tmpSum[i]重新以当前元素nums[i]开始
2)tmpSum[i]继续累加,即当前元素nums[i]+tmpSum[i-1]
问题变为求tmpSum数组的最大值
tmpSum[i] = max{nums[i], nums[i] + tmpSum[i-1]}
通俗的理解就是:
在加上当前nums[i]之前,如果tmpSum是小于0的,那么说明tmpSum起副作用,需要重新寻找起始数开始累加,即重新以当前nums[i]为起始值开始累加

代码思路

在这里,实际上可以将tmpSum数组省去,直接用一个变量递推即可,因为只和前一次结果相关。
用preSum作为以第i个元素结尾的最大连续子数组和,maxSum作为数组nums的和最大的连续子数组
遍历数组,并更新preSum,maxSum为preSum的最大值
新的preSum有两种可能,如果preSum小于0,则数组从第i个元素重新开始,否则preSum=preSum + nums[i]

代码

func maxSubArray(nums []int) int {
    len1 := len(nums)
    if 0 == len1 {
        return 0
    }

    preSum := nums[0]
    maxSum := preSum
    for i := 1; i < len1; i++ {
        if preSum < 0 {
            preSum = nums[i]
        } else {
            preSum = nums[i] + preSum
        }

        if maxSum < preSum {
            maxSum = preSum
        }
    }

    return maxSum
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/050032682387
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞