2019 China Merchants Bank M-Geeker resolve problems online game

1. The maximum and subsequence (variant)

Subject description:

5d35afc23194881188

Consider first the conventional maximum subsequence and a problem that can not be removed in the middle of a period, there is such a subject on leetcode:

leetcode-- maximum subsequence and problem solution

analyse as below:

Considering a location of elements in the array nums[i], if nums[i] + (i 前面若干个连续数组成的累计和) > nums[i], then add nums[i]later will form larger and subsequence, we put the added value is assigned nums[i], on the contrary, not dynamic nums[i]value, then this nums[i]indicates: from front to back traverse , when the position of the maximum i and subsequence ( Note: nums[i]must contain inside , comprising it represents nums[i]the maximum subsequence and, instead of the nums[:i+1]maximum and subsequence). Referring next to FIG:

5d35b9ca1814382665

And the problem we have additional conditions: You can remove the paragraph in the middle.

If we remove just the middle section, the array is divided into two sections (arrays 1, 2 arrays):

最大子序和 = 数组1从前往后遍历的最大子序和 + 数组2从后往前遍历的最大子序和

There is a problem is if a maximum sub-sequence array and not appear in the final position in the array 1, also equivalent to it? It is the equivalent, the equivalent of more than remove some, it does not affect the results. Therefore, the code can be written as:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        nums1 = nums[:]
        nums1.reverse()   # 复制一份,并反转数组
        n = len(nums)
        for i in range(1,n):
            nums[i] = max(nums[i],nums[i-1]+nums[i])      # 从前往后的最大子序和
            nums1[i] = max(nums1[i],nums1[i-1]+nums1[i])  # 从后往前的最大子序和

        # 遍历数组,找最大值
        max_ = 0
        for i in range(n-1):
            for j in range(i+1,n):
                max_ = max(max_, nums[i]+nums1[j])
        return max_

2. Matrix product of the maximum

Subject description:

5d35b9aa103ce37035

More tomorrow!

Guess you like

Origin www.cnblogs.com/anzhengyu/p/11228550.html