LeetCode Maximum Subarray
Solving LeetCode with Maximum Subarray
Original question
Returns the largest child array in an array.
Note:
Negative values
Example:
Input: nums = [-2, 1,-3, 4,-1, 2, 1,-5, 4]
Output: 6 (array [4,-1, 2, 1] and)
Solutions
It is also a classic question of dynamic planning. The following concepts are used to calculate the optimal subarray (and maximum) and dp [] at the end of the subarray using the k number, and then calculate the maximum value in dp. So what is the recursive relationship? When we put the next number num [k + 1] at the end of the number, it depends on whether the sum of the subarray connected to it is positive, if it is positive, add it; otherwise, discard it. The following code calculates the sum of dp and the maximum value in dp, so there is no additional array dp.
Another question is that the sub-array connected to num [k + 1] should be defined as multi-length, its starting position is the nearest and satisfying the sum of the subarrays connected to the number and the negative number. For example[-2, 1, -3, 4, -1, 2, 1, -5, 4]The beginning of the sub-array before-3 is 1,-1 is 4, and-5 is also 4.
AC Source Code
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 length = len(nums) current = nums[0] m = current for i in range(1, length): if current < 0: current = 0 current += nums[i] m = max(current, m) return mif __name__ == "__main__": assert Solution().maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6