leetcode Brush title - 4. Dynamic Programming

Dynamic Planning Ideas

Reference
state transition equation:
explicit "Status" -> Define Array dp / meaning of the function -> clear "selection" -> clear base case

53 and maximum subsequence

53
Given the nums an array of integers, and find a maximum sub-arrays having a continuous (subarray least one element), and to return to its maximum.

Example:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

Status: This variable is a different problem in changing the position, i.e. the subscript i.

dp [i] Meaning: each element at position i of the largest and, I think even before the judgment nums [i] <= 0, if True, the pd [i] = pd [i-1], otherwise pd [i ] = pd [i-1] + nums [i], then there PD [] is less than 0, i-1. This is because there is no understanding of the meaning of this question dp array. In fact, the correct statement should be based nums [i] and the end of the maximum continuous array.

Selected: When adding i-1 and at a maximum i.e. pd [i-1] + nums [i], or without, the maximum is at the nums i [i], because To the nums [i] at the end, so that there two options.

base case: variable (status) when I 0 =, pd [i] = nums [0].

Then the state transition equation: pd [i] = max (pd [i-1] + nums [i], nums [i])

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

Guess you like

Origin www.cnblogs.com/ivan-blog/p/12363369.html