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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值