LC.1186. Maximum Subarray Sum with One Deletion

LC.1186. Maximum Subarray Sum with One Deletion_第1张图片
求和最大的连续子数组,运行最多删除一个元素

class Solution(object):
    def maximumSum(self, arr):
        """
        left[i] 表示从左往右以arr[i] 结尾的和最大的连续子数组
        right[i] 表示从右往左以arr[i] 结尾的和最大的连续子数组
        那么对于某个元素,我们可以删除它也可以不删除它, 然后取两边和最大的部分加起来即可,
        主要边界条件即可
        """
        if len(arr) == 1:
            return arr[0]
        left, right = [float('inf')] *len(arr), [float('inf')] * len(arr)
        sumer, miner = 0, 0
        for i in range(len(arr)):
            sumer += arr[i]
            left[i] = sumer - miner
            miner = min(miner, sumer)
        sumer, miner = 0, 0
        for i in range(len(arr)-1,-1,-1):
            sumer += arr[i]
            right[i] =  sumer - miner
            miner = min(miner, sumer)

        result = -float('inf')
        
        for i in range(len(arr)):
            if i == 0:
                result = max(result, max(right[i+1], right[i]))
            elif i == len(arr)-1:
                result = max(result, max(left[i-1], left[i]))
            else:
                result = max(result, max( left[i-1] + right[i+1], left[i] + right[i] - arr[i]))
        return result

你可能感兴趣的:(LeetCode)