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

思路:如果没有delete这一操作,直接running sum+HashMap就完事了。

如果加上delete操作,还可以沿袭以上的思路,先找到 一个 subarray,然后想办法结合delete,但是很难把delete操作套进现有的模板里面

如果换个角度,看成2个subarray的结合(中间隔一个被delete的数),这样通过分别套用2次模板就实现了delete操作的嵌套了

class Solution(object):
    def maximumSum(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        def helper(a):
            res=list(a)
            su = 0
            mi = 0
            for i in range(len(a)):
                su+=a[i]
                res[i]=max(res[i],su-mi)
                mi=min(mi,su)
            return res
        forward = helper(arr)
        backward = helper(arr[::-1])[::-1]
        
        if len(arr)==1: return arr[0]
        res = max(forward)
        for i in range(len(arr)):
            if i==0:
                res = max([res, backward[i+1]])
            elif i==len(arr)-1:
                res = max([res, forward[i-1]])
            else:
                res = max([res, forward[i-1], backward[i+1], forward[i-1]+backward[i+1]])
        return res

 

你可能感兴趣的:(leetcode,hashtable)