[leetcode] 1186. Maximum Subarray Sum with One Deletion

Description

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 <= 105
  • -104 <= arr[i] <= 104

分析

题目的意思是:这道题求子数组和的最大值,但是加了一个条件,即可以删除一个数。可以分为两种情况分开处理,第一种是不删除数的连续子数组的最大值,其递推公式为:

dp1[i]=max(dp1[i-1]+arr[i],arr[i])

即当前以arr[i]结尾的连续子数组最大值等于以arr[i-1]结尾的连续子数组的最大值+arr[i],或者就是arr[i]
另一种情况是删除一个数后的最大值,其递推公式为:

dp2[i]=max(dp2[i-1]+arr[i],dp1[i-1])

即当前以arr[i]结尾的删除一个数的连续子数组最大值等于以arr[i-1]结尾删除一个数后的连续子数组的最大值+arr[i]或者就是以arr[i-1]为结尾的连续子数组和,删除arr[i]

代码

class Solution:
    def maximumSum(self, arr: List[int]) -> int:
        n=len(arr)
        dp1=[0]*n
        dp2=[0]*n
        for i in range(n):
            if(i==0):
                dp1[i]=arr[i]
            else:
                dp1[i]=max(dp1[i-1]+arr[i],arr[i])
        for i in range(n):
            if(i==0):
                dp2[i]=arr[i]
            elif(i==1):
                dp2[i]=max(arr[i],arr[i-1])
            else:
                dp2[i]=max(dp2[i-1]+arr[i],dp1[i-1])
        res=-10001
        for i in range(n):
            res=max(res,dp2[i],dp1[i])
        return res

参考文献

[LeetCode] 动态规划大法好,我发现有些题解在误导人

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值