Maximum Subarray

Given an integer arraynums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input:
 [-2,1,-3,4,-1,2,1,-5,4],

Output:
 6

Explanation:
 [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

这题最直接的可能就是贪心法。算当前的streak,如果大于0一直加,并一路上记录最大值。一旦streak掉到0以下,就从头来过。因为掉到0一下,前面的数的和就是负担了。

    def maxSubArray(self, nums):

        if len(nums) == 0:
            return 0
        currentSum = 0
        best = nums[0]
        for n in nums:
            currentSum += n
            best = max(currentSum, best)
            if currentSum < 0:
                currentSum = 0

        return best

借用prefix 法

九章上看到一个“有趣”的方法

LeetCode 的 discuss 上看到的 DP 的方法

Explanation

Although there’re some other simplified solutions, but DP solution can make the original thought for this problem clearer. In this solution, dp[i] means the largest sum among the subarrays whose last element is A[i].

Solution1. DP Solution - O(n) time, O(n) space

LeetCode 的 discuss 上看到的 Divide and conquer 的方法。好复杂

For each subarray, calculate four attributes:

The recurrence is: T(n) = 2T(n / 2) + O(1). So the running time of this algorithm is O(n).

还有一个叫 Kadane's Algorithm https://www.youtube.com/watch?v=86CQq3pKSUw

其实思想和贪心法一样的,只不过做成了DP,好理解一点。dp[i] 的定义是,sum of the maximum subarray ending at index i.

Last updated

Was this helpful?