# 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.

# Solution

Approach 1: 1D DP with 2 tables. For each element, assume we delete that, and sum up the max subarray sums ending with its left and right neighbor.

Approach 2: 1D DP with 2 tables. Keep separate tables for no deletion and at most 1 deletion.

# Code (Python)

Approach 1:

    def maximumSum(self, array: List[int]) -> int:
        # Related: maximum subarray sum -- https://leetcode.com/problems/maximum-subarray/
        if len(array) == 1:
            return array[0]
        
        # idea: for each (negative) element, assume we delete that,
        # and sum up the max subarray sums ending with its left and right neighbor
        max_from_left = [array[0]]
        for i in range(1, len(array)):
            max_from_left.append(max(array[i], max_from_left[-1] + array[i]))
        max_from_right = [0] * (len(array) - 1) + [array[-1]]
        for i in range(len(array) - 2, -1, -1):
            max_from_right[i] = max(array[i], max_from_right[i+1] + array[i])
        
        max_sum = max(max(max_from_left), max(max_from_right))
        for i in range(1, len(array) - 1):
            max_sum = max(max_sum, max_from_left[i-1] + max_from_right[i+1])
        
        return max_sum

Approach 2:

    def maximumSum(self, array: List[int]) -> int:
        # idea: keep separate tables for no deletion and 1 deletion
        if len(array) == 1:
            return array[0]
        
        no_delete = [array[0]] * len(array) # no deletes
        one_delete = [array[0]] * len(array) # at most 1 delete (including no deletes)
        
        for i in range(1, len(array)):
            no_delete[i] = max(array[i], no_delete[i-1] + array[i])
            one_delete[i] = max(array[i], one_delete[i-1] + array[i])
            if i > 1:
                one_delete[i] = max(one_delete[i], no_delete[i-2] + array[i])
        
        # need to return the max, not -1 because it doesn't have to end with the last element
        return max(one_delete)

# Code (C++)

Approach 1:

Approach 2: