Maximum Subarray Sum with One Deletion Problem
Description
LeetCode Problem 1186.
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
Solution
Approach: Kadane's Algorithm with Two States
For the maximum subarray sum without deletions, Kadane's algorithm keeps the best sum of a subarray ending at the current index: either extend the best one ending at the previous index, or start fresh with the current element.
Here we keep two such values for the subarray ending at index i:
keep: the best sum with no element deleted. As in Kadane,keep = max(keep + x, x).dropped: the best sum with exactly one element deleted. Either the deleted element isxitself, which leaves the best subarray ending just before it (the previouskeep), or the deletion happened earlier and we extend that subarray byx(the previousdropped + x). Sodropped = max(keep_before, dropped + x), computed beforekeepis updated.
The answer is the largest keep or dropped seen at any index.
The tricky case is the non-empty rule. At index 0, deleting the only element would leave nothing, so dropped starts as minus infinity, not 0. Because dropped always takes keep_before from an earlier, non-empty subarray, at least one element always remains. In Example 3, [-1,-1,-1,-1], this makes the answer -1 instead of 0.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maximumSum(self, arr: List[int]) -> int:
# keep: best sum of a subarray ending here with nothing deleted.
# dropped: best sum of a subarray ending here with exactly one element deleted
# (still non-empty); there is none yet at index 0.
keep, dropped = arr[0], float("-inf")
best = arr[0]
for x in arr[1:]:
# Either delete x (keep what ended just before it), or extend a deleted one by x.
dropped = max(keep, dropped + x)
keep = max(keep + x, x) # Kadane: extend, or start fresh at x
best = max(best, keep, dropped)
return best