[leetcode] 5182. 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
二、题解
题意:给出一串数字,返回和最大的非空子串,并且子串中最多可以删除一个数字。
题解:类似于leetcode的53题。53题可以使用动态规划的方法解出来,设dp[i]为,以下标i为结尾的子序列的最大和,那么可以得到状态转移方程dp[i+1] = {dp[i]+nums[i+1] , dp[i]>=0; nums[i+1], dp[i]<0};本题可以采用类似的思想。设dp1[i]为,以i下标为结尾的子序列的最大和,dp2[i]为,以i下标为开始的子序列的最大和,那么,最终的ans即为 max(dp1[i-1] + dp2[i+1]),其中i为arr中所有负数的下标。同时需要注意,当dp1[i-1]或者dp2[i+1]为负数时,那么可以不选择这些数字,即将dp1[i-1]或dp2[i+1]赋为0。
另外还要考虑arr全为正,全为负的特殊情况。
下面给出ac代码:
class Solution {
public:
int maximumSum(vector<int>& arr) {
vector<int> dp1(arr.size());
vector<int> dp2(arr.size());
vector<int> negative;
for(int i=0; i<arr.size(); i++){
if(arr[i]<0){
negative.push_back(i);
}
if(i==0){
dp1[i] = arr[i];
}else{
if(dp1[i-1]>0){
dp1[i] = dp1[i-1] + arr[i];
}else{
dp1[i] = arr[i];
}
}
}
for(int i=arr.size()-1; i>=0; i--){
if(i==arr.size()-1){
dp2[i] = arr[i];
}else{
if(dp2[i+1]>0){
dp2[i] = dp2[i+1]+arr[i];
}else{
dp2[i] = arr[i];
}
}
}
int ans = -9999999;
if(negative.size() == 0){
return dp1[arr.size()-1];
}
if(negative.size() == arr.size()){
for(int i=0; i<arr.size(); i++){
if(i==0){
ans = arr[i];
}else{
ans = max(ans, arr[i]);
}
}
return ans;
}
for(int i=0; i<negative.size(); i++){
int left,right;
if(negative[i] == 0){
left = 0;
}else{
left = dp1[negative[i]-1];
}
if(negative[i] == arr.size()-1){
right = 0;
}else{
right = dp2[negative[i]+1];
}
if(left < 0){
left = 0;
}
if(right < 0){
right = 0;
}
ans = max(ans, left+right);
}
return ans;
}
};