[LeetCode] 53. Maximum Subarray solving report (Python)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ttinch/article/details/102566778

Topic Address: https://leetcode.com/problems/maximum-subarray/

Title Description

Given an integer array nums, 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.

Solution 1: Dynamic Programming

d p [ i ] = d p [ i 1 ] + s [ i ] d p [ i 1 ] 0 d p [ i ] = s [ i ] d p [ i 1 ] < 0 . \begin{matrix} dp[i] = dp[i-1] + s[i] & dp[i-1] \geq 0\\ dp[i] = s[i] & dp[i-1] < 0 \end{matrix}.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        p = [0 for i in range(len(nums))]
        p[0] = nums[0]
        max_num = p[0]
        for i in range(1,len(p)):
            p[i] = p[i-1] * (p[i-1] > 0) + nums[i]
            max_num = max(max_num, p[i])
        return max_num

Solution 2: Divide and Conquer

Divide and conquer strategy:
the array are divided into two parts, the largest sub-arrays are present in:

  • The largest sub-arrays on the left side of the array
  • The largest sub-arrays on the right side of the array
  • Maximum Maximum subarray a subarray of the array to the left boundary to the right of the array to the right + left boundary to the
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        return self.solve(nums, 0, len(nums)-1)

    def solve(self, nums: List[int], low: int, high: int) -> int:
        if low == high:
            return nums[low]
        mid = low + int((high-low)/2)
        leftMax = self.solve(nums, low, mid)
        rightMax = self.solve(nums, mid+1, high)
        leftSum = nums[mid]
        tmp = nums[mid]
        for i in range(mid-1, low-1, -1):
            tmp += nums[i]
            leftSum = max(leftSum, tmp)
        rightSum = nums[mid+1]
        tmp = nums[mid+1]
        for i in range(mid+2, high+1):
            tmp += nums[i]
            rightSum = max(rightSum, tmp)
        return max([leftMax, rightMax, leftSum+rightSum])

Divide and conquer and dynamic programming differences

  • Whether overlapping sub-problems

Divide and conquer means to divide the problem into a number of independent sub-problems recursively solving each sub-problem solution of the original problem and solution of problems of sub-merged to obtain. In contrast, dynamic programming suitable for the child independent and overlapping case, that is, the sub-sub-sub-problems include a common problem.

Guess you like

Origin blog.csdn.net/ttinch/article/details/102566778