LeetCode Maximum Subarray

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.