[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] 动态规划大法好,我发现有些题解在误导人

你可能感兴趣的:(python,leetcode题解)