Maximum Subarray Sum with One Deletion in Python
1 min read

Maximum Subarray Sum with One Deletion in Python

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 

Solution:

class Solution(object):
    def maximumSum(arr):
        front = [0] * len(arr)
        back = [0] * len(arr)
        
        current_max, new_max = arr[0], arr[0]
        front[0] = arr[0]
        for i in range(1, len(arr)):
            current_max = max(arr[i], current_max + arr[i])
            new_max = max(new_max, current_max)
            
            front[i] = current_max
            
        current_max = arr[len(arr) - 1]
        new_max = arr[len(arr) - 1]
        back[len(arr) - 1] = arr[len(arr) - 1]
        
        i = len(arr) - 2
        while i >= 0:
            current_max = max(arr[i], current_max + arr[i])
            new_max = max(new_max, current_max)
            
            back[i] = current_max
            i -= 1
            
        result = new_max
        for i in range(1, len(arr)-1):
            result = max(result, front[i-1] + back[i + 1])
        return result
        
# answer 1
arr = [1,-2,0,3]
print(Solution.maximumSum(arr))

# answer 2
arr = [1,-2,-2,3]
print(Solution.maximumSum(arr))

# answer 3
arr = [-1,-1,-1,-1]
print(Solution.maximumSum(arr))