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

``````class Solution {
public:
int maximumSum(vector<int>& arr) {
int res = arr[0], n = arr.size();
vector<int> maxEndHere(n), maxStartHere(n);
maxEndHere[0] = arr[0];
for (int i = 1; i < n; ++i) {
maxEndHere[i] = max(arr[i], maxEndHere[i - 1] + arr[i]);
res = max(res, maxEndHere[i]);
}
maxStartHere[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; --i) {
maxStartHere[i] = max(arr[i], maxStartHere[i + 1] + arr[i]);
}
for (int i = 1; i < n - 1; ++i) {
res = max(res, maxEndHere[i - 1] + maxStartHere[i + 1]);
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1186

Maximum Subarray

https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/

https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/377397/Intuitive-Java-Solution-With-Explanation

https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/377522/C%2B%2B-forward-and-backward-solution-with-explanation-and-picture

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation