【leetcode】1186. Maximum Subarray Sum with One Deletion

题目如下:

Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.

Note that the subarray needs to be non-empty after deleting one element.

Example 1:

Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.

Example 2:

Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.

Example 3:

Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, 
then get an empty subarray to make the sum equals to 0.

Constraints:

  • 1 <= arr.length <= 10^5
  • -10^4 <= arr[i] <= 10^4

解题思路:假设删除arr[i]后可以获得有最大和的子数组,那么这个子数组的的和就相当于被arr[i]分成了两部分,只要找出这样的 x: i-1 >x>=0,y: i+1 <y < len(arr),使得sum(arr[x:i-1])和sum(arr[i+1:y])可以获得最大值。那么x和y怎么求呢?以x为例,只需要从下标0开始依次累计arr的和,记录出现过的和的最小值,那么sum(arr[x:i-1])的最大值就是sum(arr[0:i-1])减去出现过的和的最小值;同理,y的求法是一致的。还有两种特殊情况需要单独考虑,那就是最大的子数组只取了i的左边或者右边的部分,或者就是整个arr数组。

代码如下:

class Solution(object):
    def maximumSum(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        if len(arr) == 1:
            return arr[0]
        elif len(arr) == 2:
            return max(sum(arr), arr[0], arr[1])
        amount = arr[0] + arr[1]
        min_left = arr[0]
        left = [None, arr[0]]
        for i in range(2, len(arr)):
            left.append(max(amount, amount - min_left))
            min_left = min(amount, min_left)
            amount += arr[i]
        res = amount # set ret equals to the sum of the arr

        amount = arr[-1] + arr[-2]
        min_right = arr[-1]

        res = max(res, left[-1])  # if remove the last element
        res = max(res, left[len(arr) - 2], arr[-1], left[len(arr) - 2] + arr[-1]) # remove the second-last element

        for i in range(len(arr) - 3, -1, -1):
            right_val = max(amount, amount - min_right)
            min_right = min(amount, min_right)
            amount += arr[i]
            if left[i] == None:
                res = max(res, right_val)
            else:
                res = max(res, left[i], right_val, left[i] + right_val)
        return res

猜你喜欢

转载自www.cnblogs.com/seyjs/p/11511403.html